表单 post 无法提交。表单对象显示为空

Form post not working on submit. Form object shows null

当我通过单击保存按钮 post 表单时,它点击了 post 方法,但模型参数始终为空。

控制器

[HttpPost]
public ActionResult Edit(QuestionMaster question)
{  
    if (questionLogic.Update(model))
    {
        return RedirectToAction("List");
    } 
    return View();
}

查看:

@using (Html.BeginForm()) {
    <fieldset>
        <legend>QuestionMaster</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Question)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Question)
            @Html.ValidationMessageFor(model => model.Question)
        </div>
    </fieldset>
    <p><input type="submit" value="Save" /></p>
}

根据您上面给出的代码,您的视图缺少模型。

您可以将模型添加到视图中,如下所示:

@model QuestionMaster

此代码通常是您视图中的第一行。

除此之外,您能否解释一下控制器操作中 model 的范围? model 在哪里定义的?如果未定义,您应该明白在视图中使用 @Model.someValue 是可以的,但是在您的控制器中访问 model 将不起作用,除非您发布的模型参数被调用 model

假设这可能是您的表单 "null" 的另一个原因,请尝试将您的控制器更改为:

[HttpPost]
public ActionResult Edit(QuestionMaster question)
{  
    if (questionLogic.Update(question))
    {
        return RedirectToAction("List");
    } 
    return View();
}

在你的 EditorFor 中传递 HtmlFieldPrefix

@Html.EditorFor(model => model.Question, new ViewDataDictionary() { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "QuestionMaster" }})

这样字段的名称将是正确的,模型绑定器将能够绑定它们。

你可以按照 vortex 告诉你的去做,或者只是将你的参数名称更改为 "question"

之外的任何名称
[HttpPost]
public ActionResult Edit(QuestionMaster question2)

[HttpPost]
public ActionResult Edit(QuestionMaster model)

[HttpPost]
public ActionResult Edit(QuestionMaster anything)

您尚未发布 QuestionMaster 的模型,但从视图代码来看,它似乎包含一个名为 Question 的 属性,其类型为 string。问题是您的 POST 方法参数也被命名为 question,这会导致模型绑定失败并且对象为空。

将参数重命名为除模型中 属性 名称以外的任何名称,例如

[HttpPost]
public ActionResult Edit(QuestionMaster model)

您的模型 null 回传的原因是模型绑定的工作方式

  1. DefaultModelBinder初始化一个新的实例 QuestionMaster
  2. 然后检查已发布表单的 name/value 对。如果匹配 找到 属性 名称,设置 属性 的值。
  3. 在你的情况下你回发Question="The text you entered" 模型活页夹找到名为 question 的参数(即匹配)和 将其设置为 "The text you entered",但 question 是 typeof QuestionMaster(复杂对象,不是 string)所以绑定失败 模型变为空。