MVC模型绑定保持值为NULL
本文关键字:NULL 模型 绑定 MVC | 更新日期: 2023-09-27 18:09:18
我试图让自定义模型绑定工作,但由于某种原因,值没有设置。与工作代码相比,代码似乎很轻,但仍然没有绑定。我猜是我遗漏了一些小事。
自定义模型:
//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; }
}
DefaultModelBinder显式地作用于'Properties',而不是'Fields'
将AdminClusterCreateModel
中的public Cluster Item
改为public Cluster Item {get; set;}
应该可以达到目的。
public class AdminClusterCreateModel : BaseViewModelAdmin
{
public Cluster Item {get; set;}
public AdminClusterCreateModel()
{
Item = new Cluster();
}
}
对
这是一个微不足道的和一个角大小写,但是如果它可能对某人有所帮助:
如果你的模型有一个名为model的属性,这将导致DefaultModelBinder返回null。
public class VehicleModel
{
public string Model { get; set; }
}