MVC 3 - Checking a Client on a List

I have the following Model

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; } } 

controller

 public ActionResult Edit(int id) { return View(_db.Products.FirstOrDefault(p => p.id.Equals(id)).ProductLangs); } 

View

 @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" /> } 

I have other views and a controller where jquery unobstrusive validation works, but not here. I guess because I have a List. In fact, if I pretended with only one object, it works.

How to link jquery to unobtrusive list validation?

+4
source share
1 answer

Instead of writing these ugly foreach loops and trying to find the appropriate names for your inputs in your view, you might consider using an editor template as this will greatly simplify your view:

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

and then inside the corresponding editor template ( ~/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> 

Now you will find out that everything automatically adjusts to its place: the correct naming convention, so that when you send back, by default the connecting device will be able to restore the presentation model, work with validation on the client and server side, clear the views, happy users: - )

+4
source

Source: https://habr.com/ru/post/1339677/


All Articles