⬆️ ⬇️

Validation of datetime fields when translating a project from ASP.NET MVC 3 to ASP.NET MVC 4

Description



Recently I decided to try a new version of the ASP.NET MVC 4 platform, and transferred the project from MVC 3 to MVC 4.

And then there were unexpectedly, unexpectedly problems (although whom I cheat, switching to the beta version always means a certain risk) with validation on the client side of fields like Datetime. Suddenly, the submission refused to validate such fields, although they used to go through it, given the fact that the settings for server cultures and submissions remained the same.



In search of a problem



After some time, after I pulled out all the hair on my head from hysterics and exhausted my colleagues at work with this problem, I discovered that MVC 3 and MVC 4 use different versions of the Razor View Engine, in which EditorFor helper was performed differently. Here is an example of the use code:



@Html.EditorFor(model => model.Birthdate)



As a result, for Razor second version from MVC 4, input was created with the data_val = "true" attribute, and for MVC 3, this attribute was simply absent, which meant no validation on the client side.



Decision



I assume that the problem can be solved in two ways:



Here is an example of such a helper, so to speak in haste:

public static class DatetimeHelpers

{

public static IHtmlString Date(this HtmlHelper helper, string name, object value)

{

return Date(helper, name, value, null);

}



public static IHtmlString Date(this HtmlHelper helper, string name, object value, object htmlAttributes)

{

var tagBuilder = new TagBuilder("input");

tagBuilder.Attributes["name"] = name;

tagBuilder.Attributes["value"] = value.ToString();

tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));



return MvcHtmlString.Create(tagBuilder.ToString());

}

}



')

Here is an example of use:

@Html.Date("Birthdate", Model.Birthdate, new { id = "Birthdate" })





Perhaps you also had a similar problem, and I’m interested to know how you dealt with it.

Thanks for attention.

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



All Articles