嗯,大家好。
我有一个简短的ASP .NET MVC5问题。我必须在POST操作结果的View方法中传递ViewBag的值。
创建方法视图触发器
@Html.ActionLink("Add TestCase", "Create", "TestPlanTestCases", new { id = Model.TestPlan.ID }, null)
控制器创建GET方法
public ActionResult Create(int id)
{
var testPlanFind = _db.TestPlan.Find(id);
ViewBag.TestPlanID = testPlanFind;
ViewBag.TestCaseID = new SelectList(_db.TestCase,"ID", "Name")
return View();
}
创建视图,相关DIV:
<div class="form-group">
@Html.LabelFor(model => model.TestPlanID, "TestPlanID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ViewBag.TestPlanID.Name
@Html.ValidationMessageFor(model => model.TestPlanID, "", new { @class = "text-danger" })
</div>
控制器创建POST方法
public ActionResult Create([Bind(Include = "TestPlanID,TestCaseID")] TestPlanTestCases testPlanTestCases)
{
if (ModelState.IsValid)
{
_db.TestPlanTestCases.Add(testPlanTestCases);
_db.SaveChanges();
return RedirectToAction("Details", "TestPlans", new {id = testPlanTestCases.TestPlanID});
}
ViewBag.TestCaseID = new SelectList(_db.TestCase, "ID", "Name", testPlanTestCases.TestCaseID);
ViewBag.TestPlanID = new SelectList(_db.TestPlan, "ID", "Name", testPlanTestCases.TestPlanID);
return View(testPlanTestCases);
所以,我的问题是,在调用POST方法时,该方法始终接收TestPlanID = 0和TestCaseID =(所选测试用例的ID)。我对具有相似功能的其他控制器使用了相同的解决方法,并且工作得很好,但是由于某种原因,当涉及到设置诸如TestPlanID之类的预定义值时,它会自动设置为0,甚至不是null。 GET方法可以正常工作并传递正确的ID,但是当归结为POST方法时,出现了问题。
我希望我已提供足够的信息供您理解该问题。预先感谢!
嗯。我终于解决了它,也许不是最好的解决方案,但是它有效。
我的一个开发朋友建议解析URL以在POST方法中获取ID。因此,我决定向控制器添加3行代码,第一行分析ID值的URL,第二行将字符串转换为Int32,然后将结果值分配给testPlanTestCases.TestPlan。
更新的控制器:
public ActionResult Create([Bind(Include = "TestCaseID")] TestPlanTestCases testPlanTestCases)
{
var testPlanId = RouteData.Values["id"];
testPlanId = Convert.ToInt32(testPlanId);
testPlanTestCases.TestPlanID = (int) testPlanId;
if (ModelState.IsValid)
{
_db.TestPlanTestCases.Add(testPlanTestCases);
_db.SaveChanges();
return RedirectToAction("Details", "TestPlans", new {id = testPlanTestCases.TestPlanID});
}
ViewBag.TestCaseID = new SelectList(_db.TestCase, "ID", "Name", testPlanTestCases.TestCaseID);
ViewBag.TestPlanID = new SelectList(_db.TestPlan, "ID", "Name", testPlanTestCases.TestPlanID);
return View(testPlanTestCases);