MVC 4模型绑定返回null

时间:2014-04-15 10:47:24

标签: c# asp.net-mvc asp.net-mvc-4

我在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)
{
    ...
}

当我调试提交时,surveyResponse.Survey对象的填充应该是,但当它应该为1时,surveyResponse.Id值为0.

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

非常感谢任何帮助!

千电子伏

编辑:渲染的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:开发工具中的表单数据肯定包含&#34; Id:1&#34;。

2 个答案:

答案 0 :(得分:1)

您的代码似乎没问题。请尝试将id值明确地作为另一个参数传递,如下面的

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

  surveyResponse.Id = Id
}

答案 1 :(得分:0)

我已经测试过了。工作正常。

    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"/>
}