MVC模型绑定使值保持为NULL

时间:2013-04-16 10:38:41

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

我试图让自定义模型绑定工作,但由于某种原因,值未设置。在将它与工作代码进行比较时,代码似乎是连贯的,但它仍然没有绑定。我想这是我失踪的一些微不足道的事情。

自定义模型:

//Cluster is from Entity Framework

//BaseViewModelAdmin defines:
public List<KeyValuePair<string, string>> MenuItems;
public IPrincipal CurrentUser = null;
public Foundation Foundation; //also from Entity Framework

public class AdminClusterCreateModel : BaseViewModelAdmin
{
    public Cluster Item;
    public AdminClusterCreateModel()
    {
        Item = new Cluster();
    }
}

视图表单如下:

@using (Html.BeginForm()) {
  @Html.ValidationSummary(true)

  <fieldset>
      <legend>Cluster</legend>

      <div class="editor-label">
          @Html.LabelFor(model => model.Item.Active)
      </div>
      <div class="editor-field">
          @Html.EditorFor(model => model.Item.Active)
          @Html.ValidationMessageFor(model => model.Item.Active)
      </div>


      <div class="editor-label">
          @Html.LabelFor(model => model.Item.Name)
      </div>
      <div class="editor-field">
          @Html.EditorFor(model => model.Item.Name)
          @Html.ValidationMessageFor(model => model.Item.Name)
      </div>

      <p>
          <input type="submit" value="Create" />
      </p>
  </fieldset>
}

控制器:

[HttpPost]
public ActionResult Create(AdminClusterCreateModel model, FormCollection form)
{
    if(ModelState.IsValid) //true
    {
        var test = form["Item.Name"]; //Value is correct from form (EG: Test)
        UpdateModel(model);  //no error
    }

    //At this point model.Item.Name = null <--- WHY?

    return View(model);
}

请求群集

public partial class Cluster
{
    public Cluster()
    {
        this.Team = new HashSet<Team>();
    }

    public long Id { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime Modified { get; set; }
    public bool Active { get; set; }
    public long FoundationId { get; set; }
    public string Name { get; set; }

    public virtual Foundation Foundation { get; set; }
    public virtual ICollection<Team> Team { get; set; }
}

1 个答案:

答案 0 :(得分:8)

DefaultModelBinder在“属性”上显式工作,而不是在“字段”

上工作

public Cluster Item中将public Cluster Item {get; set;}更改为AdminClusterCreateModel应该可以解决问题。

public class AdminClusterCreateModel : BaseViewModelAdmin
{
    public Cluster Item {get; set;}

    public AdminClusterCreateModel()
    {
        Item = new Cluster();
    }
 }

此致