来自Razor中ViewModel的模型名称

时间:2016-04-01 14:59:53

标签: 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发布表单:

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

这是我的RegisterBand模型:

  public ActionResult RegisterBand(BandProfileModel model)
        {

            if (ModelState.IsValid == false)
            {
                return Json(JsonRequestBehavior.AllowGet);
            }


            return View("Index");
        }

我遇到的问题是输入字段的名称属性是BandProfile.Name,BandProfile.Genre,而不仅仅是流派和名称。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您可以更改RegisterBand ActionResult以接受ProfileViewModel

public ActionResult RegisterBand(ProfileViewModel model)
{
    if (ModelState.IsValid == false)
    {
        return Json(JsonRequestBehavior.AllowGet);
    }

    return View("Index");
}

您的HttpPost需要接受传递给表单的同一对象的实例,否则它不知道要绑定到哪个名称。

答案 1 :(得分:0)

如果您想更改控件的名称和ID,可以这样做

 @Html.EditorFor(x => x.BandProfile.Name, new { htmlAttributes = new { @class = "form-control", @id="Genre",@Name="Genre"  } })