2011-02-14 34 views
4

我有以下模式MVC 3 -

public class ProductLang 
{ 
    public int productID { get; set; } 

    public int langID { get; set; } 

    [Required, StringLength(150)] 
    public string name { get; set; } 

    [AllowHtml] 
    public string description { get; set; } 
} 

控制器

名单的客户端验证
public ActionResult Edit(int id) 
{ 
    return View(_db.Products.FirstOrDefault(p => p.id.Equals(id)).ProductLangs); 
} 

查看

@model IEnumerable<ProductLang> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    @Html.Hidden("id", Model.FirstOrDefault().productID) 

    @foreach (var productLang in Model) { 
    <div> 
     @Html.Hidden("prodLang.Index", productLang.idLingua) 
     @Html.Hidden("prodLang[" + productLang.langID + "].productID", productLang.productID) 
     @Html.Hidden("prodLang[" + productLang.langID + "].langID", productLang.langID) 

     <div class="editor-label"> 
     @Html.Label("prodLang" + productLang.langID + "__nome", "Name") 
     </div> 
     <div class="editor-field"> 
     @Html.TextBox("prodLang[" + productLang.langID + "].name", productLang.name) 
     @Html.ValidationMessage("prodLang[" + productLang.langID + "].name") 
     </div> 
     <div class="editor-label"> 
     @Html.Label("prodLang" + productLang.langID + "__description", "Description") 
     </div> 
     <div class="editor-field"> 
     @Html.TextArea("prodLang[" + productLang.langID + "].description", productLang.description) 
     </div> 
    </div> 
    } 

    <input type="submit" value="EDIT" /> 
} 

我已经得到了其他人的看法和控制器jquery unobstrusive验证工作,但不在这里。我假设是因为我有一个List。 事实上,如果我只有一个对象的视图,工作。

如何将jquery unobstrusive验证绑定到列表?

回答

4

而不是写那些丑陋foreach循环,并试图找到在你看你的投入,你可以考虑使用一个编辑模板合适的名称,因为它会让你的看法更简单的:

@model IEnumerable<ProductLang> 
@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    @Html.Hidden("id", Model.FirstOrDefault().productID) 
    @Html.EditorForModel() 
    <input type="submit" value="EDIT" /> 
} 

,然后里面相应的编辑器模板(~/Views/Home/EditorTemplates/ProductLang.cshtml):

@model ProductLang 
<div> 
    @Html.HiddenFor(x => x.idLingua) 
    @Html.HiddenFor(x => x.productID) 
    @Html.HiddenFor(x => x.langID) 

    <div class="editor-label"> 
     @Html.LabelFor(x => x.name, "Name") 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(x => x.name) 
     @Html.ValidationMessageFor(x => x.name) 
    </div> 
    <div class="editor-label"> 
     @Html.LabelFor(x => x.description, "Description") 
    </div> 
    <div class="editor-field"> 
     @Html.TextAreaFor(x => x.description) 
    </div> 
</div> 

现在你会发现,一切都自动神奇地来到自己的位置:正确的命名约定,这样,当你回发的默认模型绑定呃将能够重建视图模型,客户端和服务器端验证工作,干净的视图,开心的用户:-)