c# - MVC Razor 柱模型为空

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

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

模型...

public class ProfileModel
{

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


}

Controller ...

    [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>

有什么明显的吗?

最佳答案

您不能在模型绑定(bind)中使用 MembershipUser。模型绑定(bind)要求所有属性都有一个公共(public)的无参数构造函数,MembershipUser 的无参数构造函数是 protected 。因此,您不能直接使用它。您将需要创建自己的 View 模型来传递属性。

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

关于c# - MVC Razor 柱模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160404/

相关文章:

asp.net-mvc - MVC HtmlHelpers 与 Razor 相关的问题

c# - 使用 iText for .NET 替换 PDF 文件中的字符串

c# - MVC 4 的 BeginForm 重载中的命名参数

c# - 侵犯隐私 Checkmarx

C# 为什么在我们已经有终结器时进行处置

c# - 指定的转换对字段 int 无效

c# - 如何在 MVC 4 中触发按钮单击

asp.net-mvc - 获取 ASP.NET MVC 4 中 View 的嵌套级别

c# - 请求主视图时出现部分 View 错误

ASP.net MVC : How do I define a razor inline template in code?