MVC 剃须刀 post 型号为空

MVC razor post model is null

这里可能遗漏了一些明显的东西,但我发布到控制器的模型始终为空...模型正确传递到视图并且我可以访问属性,但是在提交表单时,模型为空。为什么?

型号...

public class ProfileModel
{

    public MembershipUser user { get; set; }
    public ProfileSettingsModel settings { get; set; }


}

控制器...

    [HttpPost]
    public ActionResult SaveSettings(ProfileModel model)
    {
        var x = model.user.UserName;
        return View();
    }

查看...

 @model MyApp.Models.Profile.ProfileModel

 @using(Html.BeginForm("SaveSettings","Profile"))
    {

        //Tried removing these as I shouldn't need them, but no luck.
        @Html.HiddenFor(x=>x.settings)
        @Html.HiddenFor(x=>x.user)

        @Html.CheckBoxFor(model=>model.settings.VisitorsCanAddMeAsFriend)
        @Html.LabelFor(x=>x.settings.VisitorsCanAddMeAsFriend, "Visitors can add me as a friend")
        @Html.CheckBoxFor(x=>x.settings.VisitorsCanMessageMe)
        @Html.LabelFor(x=>x.settings.VisitorsCanMessageMe, "Visitors can message me")

         <button id="save" type="submit" class="btn btn-default">Save</button>

     }

已渲染 HTML...

<form action="/Profile/SaveSettings?HttpMethod=POST&amp;InsertionMode=Replace&amp;LoadingElementDuration=0&amp;AllowCache=False" method="post" novalidate="novalidate">
    <input data-val="true" data-val-required="The VisitorsCanAddMeAsFriend field is required." id="settings_VisitorsCanAddMeAsFriend" name="settings.VisitorsCanAddMeAsFriend" type="checkbox" value="true">
    <input name="settings.VisitorsCanAddMeAsFriend" type="hidden" value="false">
    <label for="settings_VisitorsCanAddMeAsFriend">Visitors can add me as a friend</label>
    <input data-val="true" data-val-required="The VisitorsCanMessageMe field is required." id="settings_VisitorsCanMessageMe" name="settings.VisitorsCanMessageMe" type="checkbox" value="true">
    <input name="settings.VisitorsCanMessageMe" type="hidden" value="false">
    <label for="settings_VisitorsCanMessageMe">Visitors can message me</label>                 
    <button id="save" type="submit" class="btn btn-default">Save</button>
</form>

有什么明显的吗?

改变

@Html.HiddenFor(x=>x.settings)
@Html.HiddenFor(x=>x.user)

@Html.HiddenFor(x => x.user.UserName)

默认活页夹至少应该选择那个。

我不认为你可以做 html.hiddenfor(复杂类型),因为值必须表示为字符串。在您的渲染 html 中,您可以看到两个 HiddenFor 没有被渲染为输入类型='hidden' ...../

所以是的,明显的错误是两个html.hiddenfor。您将需要执行一个 HiddenFor 或您希望在 post

中接收的每个 属性

您不能在模型绑定中使用 MembershipUser。模型绑定要求所有属性都有一个 public 无参数构造函数,MembershipUser 的无参数构造函数是受保护的。因此,您不能直接使用它。您将需要创建自己的视图模型来传递属性。

因此,删除设置和用户 HiddenFor's,然后直接对这些属性进行出价将得到您想要的。

在控制器的回发方法中,最后一行说

return View();

但它应该说

return View(model);

否则您不会将模型传回页面。