MVC 4模型绑定返回null

本文关键字:返回 null 绑定 模型 MVC | 更新日期: 2023-09-27 17:58:35

我在MVC中的模型绑定方面遇到了问题。我有一门课:

public class UserSurvey
{
    public int Id { get; set; }
    public virtual Survey Survey { get; set; }
}

哪个是视图的模型:

@model SurveyR.Model.UserSurvey
<form id="surveyForm">
    <div class="container survey">
        @Html.HiddenFor(x=>x.Id)
        @Html.EditorFor(x => x.Survey.Steps)
    </div>
    <input type="button" value="Submit" id="btnSubmit"/>
</form>

然后对于提交,控制器采用一个类:

public class SurveyResponseViewModel
{
    public int Id { get; set; }
    public Survey Survey { get; set; }
}
[HttpPost]
public ActionResult Submit(SurveyResponseViewModel surveyResponse)
{
    ...
}

当我调试submit时,surveyResponse.Survey对象会按原样填充,但surveyResponse.Id值应为1时为0。

我可以看到Id=1在提交中被传递回来,但模型绑定似乎没有将其连接起来。

如有任何帮助,我们将不胜感激!

Kev

编辑:渲染的html看起来像这样:

<form id="surveyForm">
    <div class="container survey">
        <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="1" />

因此,是的,如果我使用开发工具查看,该值会出现在那里,并且也会在提交中传递。

编辑2:开发工具中的Form数据肯定包含"Id:1"。

MVC 4模型绑定返回null

您的代码似乎很好。尝试将id值显式地作为另一个参数传递,如下面的

[HttpPost]
public ActionResult Submit(SurveyResponseViewModel surveyResponse , int Id )
{
  surveyResponse.Id = Id
}

我已经测试过了。它运行良好。

    public ActionResult test1()
    {
        var model = new UserSurvey();
        model.Id = 10;
        return View(model);
    }
    [HttpPost]
    public ActionResult test1(SurveyResponseViewModel surveyResponse)
    {
        var x = surveyResponse.Id; // returns 10
        return View(new UserSurvey());
    }
    public class SurveyResponseViewModel
    {
        public int Id { get; set; }
        public Survey Survey { get; set; }
    }
    public class UserSurvey
    {
        public int Id { get; set; }
        public virtual Survey Survey { get; set; }
    }
    public class Survey
    {
        public string Steps { get; set; }
    }
@model TestWeb.Controllers.UserSurvey
@using (Html.BeginForm())
{
    <div class="container survey">
        @Html.HiddenFor(x=>x.Id)
        @Html.EditorFor(x => x.Survey.Steps)
    </div>
    <input type="submit" value="Submit" id="btnSubmit"/>
}