【问题标题】:Model names from ViewModel in RazorRazor 中 ViewModel 的模型名称
【发布时间】:2016-07-21 10:53:03
【问题描述】:

我有以下 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,而不仅仅是 Genre 和 Name。

我该如何解决这个问题?

【问题讨论】:

  • 除了接受的答案外,您还可以使用public ActionResult RegisterBand([Bind(Ptefix = "BandProfile")] BandProfileModel model),它在绑定时有效地去除前缀

标签: c# asp.net asp.net-mvc razor model-binding


【解决方案1】:

您可以将 RegisterBand ActionResult 更改为接受 ProfileViewModel

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

    return View("Index");
}

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2016-09-30
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2013-11-10
      相关资源
      最近更新 更多