我花了最近2天试图弄清楚,基本上我有两个模型(Event和EventStyle),但是EventStyle一个不会绑定,不管我尝试什么。MVC3模型绑定外键
这些类是Code-First数据库的一部分,而Event模型具有EventStyle的外键。
这里是我的淡化型号:
public class Event {
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual EventStyle Style { get; set; }
}
public class EventStyle {
public string Id { get; set; }
public string Image { get; set; }
}
在我的控制器我有这样的:
[HttpPost]
public ActionResult Create(Event evt) { /* add evt to the database */ }
和一个简单的形式:
@using (Html.BeginForm()) {
@Html.HiddenFor(evt => evt.Id)
@Html.HiddenFor(evt => evt.Style)
@Html.TextBoxFor(evt => evt.Name)
@Html.TextAreaFor(evt => evt.Description)
}
(其实我有一个custom @ Html.EditorFor for evt.Style它改变了隐藏字段的值)
表单提交时,事件与Id
,Name
和Description
正确绑定。 但是,即使数据库中的隐藏字段包含有效的EventStyle
ID,Style
属性仍为空。
如果我删除的隐藏字段,然后风格成为默认的一个(如事件的构造函数中设置)
我也尝试使用上EventStyle一个ModelBinder
,但正确的ID还没有出现过bindingContext
,这可能是问题的一部分。
但是,正确的ID确实通过控制器中的活页夹controllerContext
或直接使用FormCollection
。我宁愿让ModelBinding正常工作。
也许ModelBinder对我的数据库没有任何认识?如果是这样,我怎么才能让它识别我的数据库?
编辑:嗯只是删除了virtual
现在的活页夹从形式拿起正确的ID,但它仍然没有得到对事件模型的
EDIT2:解决,以此来加载从该EventStyle数据库:
if (evt.Style != null) {
evt.Style = db.EventStyles.Find(evt.Style.Id);
}
呵呵我忽略了,它似乎在工作,谢谢! 虽然,它不会从数据库中加载Id。我必须通过'event.Style.Id'手动执行此操作吗? – Jorticus 2011-12-28 12:20:16
@Jorticus默认的modelbinder不具备数据库的知识,它的目的是简单地在你的模型中设置在Params中找到的属性。不建议给你的模型绑定器数据库知识。 – Craig 2011-12-28 12:25:26