MVC3 editor template does not generate client-side validation

I have a problem, basically I have a form with a lot of fields in it, and all of them have the necessary set of attributes, so when you just leave it blank and click "OK", you will receive a confirmation on the client side, and it turns red. This word is great for everything except EditorTemplate.

My model:

public class MyModel { [Required] public string Username{get;set;} public Location Loc{get;set;} } public class Location { [Required] public string Loc1{get;set;} [Required] public string Loc2{get;set;} } 

I have the following in my main view:

 @Html.EditorFor(m => m.Location, Model.Location) 

And here is my editor:

 <tr> <td class="editor-label"> @Html.LabelFor(m => m.Loc1) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.Loc1, Model.Locs==null?Enumerable.Empty<SelectListItem>():Model.Locs, "---select--", new { @class = "location-ddl" }) </td> <td> @Html.ValidationMessageFor(m => m.Loc1) </td> </tr> 

...

After I explored it, I noticed that HTML is prodcues:

 <select name="Location.Loc1" id="Location_Loc1"> 

As you can see, it lacks some attributes for client-side validation, usually it should be something like this:

 <select name="Loc1" id="Loc1" data-val-required="The Loc1field is required." data-val="true"> 

My question is why the editor template does not generate the correct html output with client-side validation and how to fix it?

Just for the record, it works on the server side, so if these selections are empty on the server side, it will be marked as empty and sent back. Nevertheless, I would like to understand the behavior of the editor form and how to fix it.

thanks

+4
source share
2 answers

You can use Html.GetUnobtrusiveValidationAttributes("Location.Loc1") to get validation attributes. See the documentation here .

+1
source

I think the use of Html.GetUnobtrusiveValidationAttributes() should be explained in more detail.

Assuming your Location editor template model, you needed to add the following code block to the top of the file:

 @{ IDictionary<string, Object> htmlAttributeValuePairsLoc1 = Html.GetUnobtrusiveValidationAttributes(Html.NameFor(m=>m.Loc1).ToHtmlString()); htmlAttributeValuePairsLoc1.Add("class","location-ddl"); IDictionary<string, Object> htmlAttributeValuePairsLoc2 = Html.GetUnobtrusiveValidationAttributes(Html.NameFor(m=>m.Loc1).ToHtmlString()); htmlAttributeValuePairsLoc2.Add("class","location-ddl"); } 

Now you can enter the appropriate dictionary in your HtmlHelpers, for example:

 <tr> <td class="editor-label"> @Html.LabelFor(m => m.Loc1) </td> <td class="editor-field"> @Html.DropDownListFor(m => m.Loc1, Model.Locs??Enumerable.Empty<SelectListItem>(), "---select--", htmlAttributeValuePairsLoc1) </td> <td> @Html.ValidationMessageFor(m => m.Loc1) </td> </tr> 

PS Html.NameFor() appeared in MVC4, but you can get the property name using Reflection.

0
source

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


All Articles