首页 > 解决方案 > ASP POST ActionResult 收到 0 而不是提供的 ID 值

问题描述

嗯,大家好。

我有一个简短的 ASP .NET MVC5 问题。我必须从 View 方法中的 ViewBag 中传递一个带有 POST 操作结果的值。

创建方法视图触发器

@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 方法时,出现了问题。

在视图中创建 GET 方法的结果 调试:TestPlanID 和 TestCaseID 的值

我希望我已经提供了足够的信息让你理解这个问题。提前致谢!

标签: c#asp.netasp.net-mvcasp.net-mvc-5

解决方案


出色地。我终于解决了它,也许不是最好的解决方案,但它有效。

我的一个开发朋友建议解析 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);

推荐阅读