Sunday, October 23, 2011

ASP.Net MVC Client Validation For Dynamically Added Form

This is how I have implemented the client side validation with MVC3 client side validation with JQuery validation plugin. The requirement was to create a model dialog with a form which is loaded via an Ajax request to the server.

  1. Enable client validation in web.config
We need to enable client side validation in web.config application settings section like thism

          <add key="ClientValidationEnabled" value="true"/>
        <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

    2 The form
 In your form you need to have a FormContext otherwise it will not generate validation attributes.  If the FormContext is null we need to create a new FormContext  like this in your view.
@{using (Html.BeginForm("Create", "Person", FormMethod.Post)
      if (this.ViewContext.FormContext == null)
          this.ViewContext.FormContext = new FormContext();
    // .....

    3 Phrase validation attributes 
 Then after the ajax request we need to phrase validation attributes using JQuery like this,<br />
$.get("@Url.Action("Create", "Person")", null, function (data) {

Saturday, October 22, 2011

Creating Categorized/Grouped Autocomplete Menu with JQuery

JQuery has given you a nice extendable library to create auto complete. But what if you want to customize it to have something like Facebook search autocomplete menu.  Here I have gathered several features of JQuery to make this customization. Here is my JQuery with MVC3 but you can use whatever the backend which you can return a array of Json objects like this,
Here is my Search action in SearchController

And here is my JQuery code,