C# razor中ViewModel中的模型名称
我有以下ViewModel:C# razor中ViewModel中的模型名称,c#,asp.net,asp.net-mvc,razor,model-binding,C#,Asp.net,Asp.net Mvc,Razor,Model Binding,我有以下ViewModel: public class ProfileViewModel { public BandProfileModel BandProfile { get; set; } public MusicanProfileModel MusicianProfile { get; set; } public RegularProfileModel RegularProfile { get; set; } } 我在视图中使用此ViewModel发布表单: @
public class ProfileViewModel
{
public BandProfileModel BandProfile { get; set; }
public MusicanProfileModel MusicianProfile { get; set; }
public RegularProfileModel RegularProfile { get; set; }
}
我在视图中使用此ViewModel发布表单:
@using (Ajax.BeginForm("RegisterBand", "NewProfile", new AjaxOptions() { HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
Bandname
</div>
<div class="col-md-10">
@Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(x => x.BandProfile.Name, "", new { @class = "text-danger" })
</div>
</div>
我的问题是输入字段的name属性是BandProfile.name,BandProfile.Genre,而不仅仅是Genre和name
如何解决此问题?您可以更改
注册表和
操作结果以接受ProfileViewModel
public ActionResult RegisterBand(ProfileViewModel model)
{
if (ModelState.IsValid == false)
{
return Json(JsonRequestBehavior.AllowGet);
}
return View("Index");
}
您的
HttpPost
需要接受传递到表单中的同一对象的实例,否则它将不知道绑定到哪个名称 如果要更改控件的名称和id,可以这样做
@Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control", @id="Genre",@Name="Genre" } })
除了可接受的答案外,您还可以使用
公共操作结果寄存器带([Bind(Ptefix=“BandProfile”)]BandProfileModel)
在绑定时有效地去除前缀
@Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control", @id="Genre",@Name="Genre" } })