Asp.net mvc 4 MVC4Get posted主键
我的问题是如何从controller1中的POST方法中获取自动递增的主键,并将其用作controller2中的get方法中的外键 目前所有的代码都是用EF生成的,我首先使用数据库 我想我必须在controller2中编辑GET方法,它看起来像这样Asp.net mvc 4 MVC4Get posted主键,asp.net-mvc-4,post,get,Asp.net Mvc 4,Post,Get,我的问题是如何从controller1中的POST方法中获取自动递增的主键,并将其用作controller2中的get方法中的外键 目前所有的代码都是用EF生成的,我首先使用数据库 我想我必须在controller2中编辑GET方法,它看起来像这样 // GET: /Question/Create public ActionResult Create() { ViewBag.TestId = new SelectList(db.Tests, "TestId"
// GET: /Question/Create
public ActionResult Create()
{
ViewBag.TestId = new SelectList(db.Tests, "TestId", "TestTitle");
return View();
}
这个函数返回一个TestTitles列表
我所需要的只是返回当前会话中最后插入的“testId”或相同插入的“testId”。它是一个整数。我该怎么做 创建一个同名的ActionResult,因为您没有使用模型,所以只需从
FormCollection
类中获取值即可
假设您的selectlist
是这样创建的
@Html.DropDownListFor("TestId",ViewBag.TestId);
为同一视图定义另一个操作,如下所示:
[HttpPost]
public ActionResult Create(FormCollection formData)
{
formData["TestId"]
return View();
}
不过,我强烈建议使用模型,并避免使用ViewBag。保存对象后,您可以从对象中获取id:
db.Foos.Add(foo);
db.SaveChanges();
var pk = foo.Id;
至于如何传递这个消息,假设您正确地遵循了GET POST重定向模式,您需要将它包含在URL中,以便进行重定向。具体操作方式取决于您的动作签名和路线,但通常您会执行以下操作:
return RedirectToAction("SomeAction", new { id = foo.Id });
我没有试图在get方法中获取ID,而是发现我也可以找到它,并在POST方法中使用它,在该方法中我将信息插入数据库。通过使用Lambda表达式查找最后插入的ID,可以插入外键的正确值。在我改进结构之前,这可能是我的临时解决方案
[HttpPost]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
question.TestId = db.Tests.OrderByDescending(t => t.TestId).FirstOrDefault().TestId;
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TestId = new SelectList(db.Tests, "TestId", "TestTitle", question.TestId);
return View(question);
}`
不要增加它,只需在插入记录后获取最后一个插入ID,并将其传递给第二个控制器操作。