【发布时间】:2013-04-17 19:07:47
【问题描述】:
我正在尝试使自定义模型绑定起作用,但由于某种原因,未设置这些值。将代码与工作代码进行比较时,该代码似乎是合法的,但它仍然没有绑定。我想这是我缺少的一些微不足道的事情。
自定义模型:
//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; }
}
【问题讨论】:
-
我们可以看看你的集群类吗? Item.Name 绝对是公共属性而不是公共字段吗?已经有一段时间了,但 IIRC 它只会绑定到属性。
-
我已将其添加到问题中
-
您是否检查过
UpdateModel中是否有更新model.Item的内容? -
@HugoDelsing 默认情况下'DefaultModelBinder'开始发挥作用,并从'FormCollection'构造动作方法参数中的对象。有一种方法可以通过“自定义模型绑定器”(相关codeproject.com/Articles/228826/ASP-NET-MVC-Model-Binders)更改特定类型的绑定工作。我问这个问题是因为我可能误读了“我正在尝试让自定义模型绑定工作”。现在我认为没有“自定义活页夹”,而“DefaultModelBinder”仍在发挥作用。在这种情况下,您可能想要更改“公共集群项目;” to '公共集群项目 {get;放;};'让它发挥作用。
-
谢谢!确实
public Cluster Item {get; set;}足以让它发挥作用。我对误导性信息表示歉意。我绑定到一个自定义模型,所以这就是我使用该术语的原因。如果您将其发布为答案,我会接受。
标签: c# asp.net-mvc-4