ASP POST ActionResult 收到 0 而不是提供的 ID 值

ASP POST ActionResult recieves a 0 instead of a provided ID value

好了,大家好。

我有一个简短的 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 行额外的代码,第一行解析 URL 的 ID 值,第二行将字符串转换为 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);