gpt4 book ai didi

c# - MVC Razor 柱模型为空

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:24 25 4
gpt4 key购买 nike

可能在这里遗漏了一些明显的东西,但我发布到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com