MVC4 : From Ajax Helper to jQuery and Knockout
In our MVC4 sprint; we used ASP.NET bundling for CSS / JS resources and migrated all the Ajax.BeginForm / Ajax.EndForm based forms that were developed in MVC2 days to the current techniques
In our MVC3 sprint; we removed MicrosoftMvcValidation.js and MicrosoftMvcJQueryValidation.js files from MVC2 days and instead referenced jQuery.Validation and Microsoft.jQuery.Unobtrusive.Validation NUGET references for jquery.validate.js and jquery.validate.unobtrusive.js respectively and as we were also using Ajax helpers; we added Microsoft.jQuery.Unobtrusive.Ajax NUGET packages for jquery.unobtrusive-ajax.js
We made the jqueryval bundle as its get created if we create a new MVC4 project and updated global.asax accordingly. Note how jquery.validate* bundle gets created; if –ajax .js files exist; they also get included in this same bundle. Once its in place our existing Ajax Helper based forms looked like this
We can use jQuery for Ajax requests and given unobtrusive validation works with jQuery (through jQuery.Validate plugin) we don’t need Ajax Helpers. Our example form will look like this:
- Note that unobtrusive validation will not work and instead server side’s validation will work and error message can be sent from the server; in the next Knockout example; we will use the validation
- Note that for “Title” field we used HTML helpers for unobtrusive validation and for that to work; we need to call jquery.validate’s valid() method in our postNewItem()
- Note that for “Text” field we are not using HTML helpers and server side validation will work for this
- Note that using “lower” level HTTP status codes at server side and using jQuery's declarative style to handle / separate these “exceptional case”; we can write separate functions to handle different Status Codes; take a look at my HttpStatusCodeResult post
We need to take care of these bad smells next
- Client side validation has become spaghetti; mix of server side (HTML.TextBoxFor() + HTML.ValidationMessageFor()) and client side ( $(“form”).valid() )
- For Knockout data-bind attributes; unfortunately we cant use Html.EditorFor() as there is no suitable override to add additional HTML attributes; that’s why I used HTML.TextBoxFor() above!
Post your ideas in the comments below; in the next post I will write about what we did in the final sprint!