验证用于在MVC中导航性能(4)和EF(4) [英] Validation for Navigation Properties in MVC (4) and EF (4)
问题描述
我创建了一个EF模型,然后创建了一个MVC控制器和视图。
该机型 A
有一个导航属性键入 B
。所以,当我创建 A
我要选择一个 B
。
I created a model with EF and then created a controller and view in MVC.
The model type A
has a Navigation Property to type B
. So when I create A
I want to select a B
.
MVC的向导来创建控制器和视图,标量属性只创建的字段。于是我去了,改变了我创建行动 A
来:
The MVC wizard to create the controller and view only created fields for Scalar Properties. So I went and changed my create action on A
to:
public ActionResult Create() //Create action for A
{
List<B> b = db.B.ToList(); //db is my DataContext
ViewData["B"] = companies.Select(option => new SelectListItem
{
Text = (option.Name.ToString()),
Value = (option.Id.ToString())
});
return View();
}
和加入到我的观点:
<div class="editor-label">
@Html.LabelFor(model => model.B)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.B, (IEnumerable<SelectListItem>)ViewData["B"], "---- Select B ----")
@Html.ValidationMessageFor(model => model.B)
</div>
全部是迄今为止很好,我得到的HTML
All is good so far and I get the HTML
<select class="valid" id="B" name="B">
<option value="">---- Select B ----</option>
<option selected="selected" value="1">TestB</option>
</select>
然而,当我提出我的错误:
However when I submit I get the error:
The value '1' is invalid.
已经不写它必须是自动生成的某处任何验证。如何纠正它来检查值对计算机[B]集合ID的?
Having not written any validation it must have been auto-generated somewhere. How do I correct it to check the values against the ViewData["B"] collection ID's?
推荐答案
问题是你的下拉列表中的值为编号
- 但属性是 B
。
The problem is the value of your dropdown list is Id
- but the property is a B
.
您应该绑定到你的导航属性的FK来代替。我不知道你的模型(如果这没有帮助,你应该将它张贴)
You should bind to the FK of your navigation property instead. I'm not sure of your model (if this doesn't help you should post it)
<div class="editor-field">
@Html.DropDownListFor(model => model.BId, (IEnumerable<SelectListItem>)ViewData["B"], "---- Select B ----")
@Html.ValidationMessageFor(model => model.BId)
</div>
请注意我已经改变了 model.B
到 model.BId
Note I've changed model.B
to model.BId
这篇关于验证用于在MVC中导航性能(4)和EF(4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!