ASP.NET MVC Partial View Validation From Client Side

I have come across one problem regarding client side validation for form submit where form resides in partial view
I have gone through many forums and articles but very few have explained it with complete example

Guess what I have done? Made one simple and small demo that I am going to explain

How unobtrusive validation works and problem associated with partial view
  • Unobtrusive validation is a unique feature. One can easily bind server side validation to client side validation provided by JQuery plugin.
  • Unobtrusive validation binds special attributes to field on load event, which are used to bind your own rules defined inside the model with rules implementation provided by JQuery library.
  • However, when you create a partial view fields in new form are without those special attributes and so validation is not working.
  • One of the solution is to load unobtrusive .js file again. It works but you need to load something twice wasting resources.
  • There is a method “parse” in unobtrusive plugin , which is responsible for creating validation
  • There is a method “parse” in unobtrusive plugin , which is responsible for creating validation attributes , adapters and also what’s really important errorPlacement adapter. Everything you need. Knowing all of this we can just use this “parse” on the form and everything should work fine.

Higher level we could divide this exercise in three sections moving forward step by step we are going to try to accomplish each section

Section 1 : Setup & Configuration

  • STEP 1 : Bundle following files in BundleConfig class BundleConfig
    • JQuery (for DOM management)
    • JQuer UI (for Dialogue box)
    • jquery.unobtrusive & jquery.validate (for validation)
    • “~/Content/css” for site.css (for site design)
    • “~/Content/themes/base/css” JQuery UI CSS (for dialogue box design)
  • STEP 2 : _layout page  _layout
    • Add STEP 1 bundles in _layout page
    • Note replace render section of script to bottom after jquery, jqueryui & jqueryval bunder
  • STEP 3 : Add appsettings in web.config  Web.config
    • set ClientValidationEnabled true
    • set UnobtrusiveJavaScriptEnabled true

#Section 1 is completed let us move forward to section 2


Section 2 : Back-end side

  • STEP 1: AddUserViewModel Model that includes following  Model
    • Properties
    • validate properties using DataAnnotations using System.ComponentModel.DataAnnotations
  • STEP 2: Create partial view incorporates followings  Partial View
    • Associated Model
    • Form elements without submit as it will be taken care of by dialogue box button
    • Validation message
  • STEP 3: HomeController has two responsibilities  HomeController
    • Render partial view (i.e. AddUserPartialView)
    • Handle submit data on form POST (i.e. AddUserInfo)

#Section 2 is completed let us move forward to section 3


Section 3 : Front end side (Index.chtml)

  • STEP 1: Add dialogue box container and adduser button Ref Code
  • STEP 2: Add button click event to open dialogue box (i.e. $(“#AddUserForm”).dialog({…}) Ref Code
  • STEP 3: Load rendered partial view in dialogue box
    • (i.e. $(‘#AddUserForm’).load(‘@Url.Action(“AddUserPartialView”, “Home”)’, function () {…}) ) Ref Code
  • STEP 4: Call “parse” in unobtrusive plugin, which is responsible for creating validation attributes Ref Code
  • STEP 5: Register form submit event on load of dialogue box (i.e. $form.submit(function () {..}) ) Ref Code
  • STEP 6: post serialized form data to /Home/AddUserInfo action by AJAX Ref Code
  • STEP 7: AJAX event has two handlers success and error Ref Code
  • STEP 8: Last but not the least add two buttons “Add User” and “Cancel” in dialogue box Ref Code
    • “Add User” call form submit
    • “Cancel” close dialog box

Source code:-
https://github.com/ganesha8shiva/MVCPartialViewValidation
Video Help :-


Note: If anybody faces error while building project

  • Right click on solution
  • Enable NuGet Package Restore (will take few minutes to finish)
  • Tools -> Library Package Manager -> Package Manager Console
  • Some NuGet Packages are missing from this solution. Click to restore.
  • Press Restore (will take several minutes)
  • Build Successful and works like charm

Video Help :-

Advertisements

What Is Document Ready Event In JQuery ???

What is the role of below code in JQuery? For me it is always be part of understanding JQuery fundamentals

$(document).ready(function(){
   // jQuery methods go here...
});

Lets run below sample code and you wonder!!!
Why we get first alert “Alert 2” and second alert “Alert 1”
Interesting !!! Correct…

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  alert("Alert 1");
});
alert("Alert 2");
</script>
</head>
<body></body>
</html>

Reason…guess????

$(document).ready(function(){
   // jQuery methods go here...
});

This code prevent any jQuery code from running before the document is finished loading (is ready).Good practice is to wait for the document to be fully loaded and ready before start working with it. This also allows developer to have JavaScript code before the body of document, in the head section.

Here are few examples of actions that can fail if methods run before the document is fully loaded:

  • Trying to hide an element that is not created yet
  • Trying to get the size of an image that is not loaded yet

Note: JQuery team has also made an even shorter method for the document ready event:

$(function(){
   // jQuery methods go here...
});

JQuery Virtual Keyboard

A quick post on virtual keyboard which can be used to enter user name / password / Pine number, etc… Internet banking highly recommend to use while logging into Internet Banking Site.

Below are the advantages of virtual keyboard

  • The virtual keyboard can be an additional precautionary measure, protects you against malicious key logger programs which might have infected your  computer.
  • A key logger program can capture the keystrokes you enter in the physical keyboard to login which may be accessing your PC without your knowledge or permission.
  • A virtual keyboard prevents your username or password from being stolen, especially while using public computers, such as those available in Internet cafes. Also, the sequence in which the keys appear will change everytime the page is refreshed.

Before I start with an example go through Keith Wood’s solution for it build on top of JQuery

It is very clean, well documented, higly compatible and scalable solution, if I have to rate, I rate 5 out of 5 stars and highly recommended solution

Virtual Keyboard:  http://keith-wood.name/keypad.html

Quick Reference: http://keith-wood.name/keypad.html

jQuery Keypad Reference:     http://keith-wood.name/keypadRef.html

Last but not the least I am going through simple yet quick example before signing off

Step 0:- Create Folder structure as below

  • main
  • main/css
  • main/javascript

Step 1:-  Add jquery.keypad.css in main/css folder

Step 2:-  Add jquery-1.7.1.min.js and jquery.keypad.js in main/javascript folder

Step 3:-  Add index.html in main folder and copy-paste below code into index.html  “please read code carefully before copying it blindly :D”

<html>
<title>Virtual Keyboard</title>
<head>
 <link type="text/css" href="css/jquery.keypad.css" rel="stylesheet" />  
 <script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
 <script type="text/javascript" src="javascript/jquery.keypad.js"></script> 
    <script type="text/javascript">
        $(document).ready(function () {                    
            $("input[id$='chkKeyboard']").click(function () {            
                if (!$(this).is(':checked')) {
                    $('#txtUsername').keypad('destroy');
                    $('#txtPassword').keypad('destroy');
                } else {
                    $('#txtUsername').keypad({ keypadOnly: true, layout: $.keypad.qwertyLayout, randomiseAlphabetic: true, randomiseNumeric: true, randomiseOther: true });
                    $('#txtPassword').keypad({ keypadOnly: true, layout: $.keypad.qwertyLayout, randomiseAlphabetic: true, randomiseNumeric: true, randomiseOther: true });                    
                }
            });
        });
    </script>       

</head>

<body>
   <div style="text-align: left; margin-top: 15px;">                           
      Username : <input type="text" id="txtUsername" /><br/>
      Password : <input type="Password" id="txtPassword"></asp:TextBox><br/>
      <input type="checkbox" id="chkKeyboard" /> Use virtual keyboard (Recommended)<br/>
      <input type="button" id="btnSubmit" value="Submit"  />
   </div>
</body>

</html>

Step 4:- Open index.html in any browser (ie, chrome, firefox, etc…)
virtual_keyboard

Quote: “Great solutions are described in few words”

What is Remote Attribute?

Underline Problem:-
Any identity thing is unique example userid / emailid / username so to validate uniqueness we have to compare id with existing data
(most obvious database)

Solution:-
Decorating a model property with this attributes will instruct JQuery validate to make an HTTP request to a given action method
for server-side checking. The result is transmitted back to the client and an error message will be displayed before the form is
submitted

We are taking even number example entered at user-end
Create A View

@model MvcApplication1.Controllers.Category
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@{Html.EnableClientValidation(true);}
@using (Html.BeginForm("Create", "Employee", FormMethod.Post))
{
   @Html.ValidationSummary(false)
   @Html.LabelFor(m => m.PIN)
   @Html.TextBoxFor(m => m.PIN, new { maxlength=1  }) <br />        
   <input type="submit" value="Submit" />
}

Create A Model

public class Category
{
   [Remote("IsEvenNumber", "Employee", ErrorMessage = "Enter Even Number")]
   public int PIN { get; set; }
}

Create A Controller

public class EmployeeController : Controller
{
   [HttpGet]
   public ActionResult create()
   {
      return View();
   }
   public JsonResult IsEvenNumber(int PIN)
   {
      return Json(PIN % 2 == 0, JsonRequestBehavior.AllowGet);
   }
}

I can see AJAX request for validation on onkeyup for each character type in textbox
instead of tab (onBlur)

<script language="javascript" type="text/javascript">
$.validator.setDefaults({
onkeyup: false
})
</script>

What is the user of AdditionalFields attributes?

Use to send multiple values to action for validation

------------------------------------------------
Model
------------------------------------------------
public class Category
{
   [Required]
   [Remote("IsEvenNumber", "Employee", AdditionalFields = "hide_pin", ErrorMessage = "Enter Even Number & Not correct pin")]   
   public int PIN { get; set; }
}

------------------------------------------------
View
------------------------------------------------
@model MvcApplication1.Controllers.Category
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<script language="javascript" type="text/javascript">
    $.validator.setDefaults({
        onkeyup: false
    })
</script>

@{Html.EnableClientValidation(true);}
@using (Html.BeginForm("Create", "Employee", FormMethod.Post))
{
    @Html.ValidationSummary(false)

    @Html.LabelFor(m => m.PIN)
    @Html.TextBoxFor(m => m.PIN, new { maxlength = 4 }) <br />

    @Html.Hidden("hide_pin", "10")
    <input type="submit" value="Submit" />
}

------------------------------------------------
Controller
------------------------------------------------
public class EmployeeController : Controller
{
   [HttpGet]
   public ActionResult create()
   {
      return View();
   }

   public JsonResult IsEvenNumber(int PIN, int hide_pin)
   {
      return Json(PIN % 2 == 0 && PIN == hide_pin, JsonRequestBehavior.AllowGet);
   }
}

JQuery

JQuery is the library of JavaScript, it is lightweight “write less, do more” JavaScript library, compatible with all popular browser i.e. IE 9 / 10, Firefox, Chrome, Safari, etc.

  • The jQuery library contains the following features:
  • HTML element selections
  • HTML element manipulation
  • CSS manipulation
  • HTML event functions
  • JavaScript Effects and animations
  • HTML DOM traversal and modification AJAX Utilities

How to add JQuery? Very Simple if we know how to .js file

<script type=”text/javascript” src=”jquery.js”></script>

Rather further due we straight jump in JQuery Syntax

jQuery Selectors


jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element.


jQuery Selectors

It is a key point to learn how jQuery selects exactly the elements you want to apply an effect to.

jQuery selectors allow you to select HTML elements (or groups of elements) by element name, attribute name or by content.

lamp In HTML DOM terms:Selectors allow you to manipulate DOM elements as a group or as a single node.

jQuery Element Selectors

jQuery uses CSS selectors to select HTML elements.

$(“p”) selects all <p> elements.

$(“p.intro”) selects all <p> elements with.

$(“p#demo”) selects all <p> elements with id=”demo”.


jQuery Attribute Selectors

jQuery uses XPath expressions to select elements with given attributes.

$(“[href]”) select all elements with an href attribute.

$(“[href=’#’]”) select all elements with an href value equal to “#”.

$(“[href!=’#’]”) select all elements with an href attribute NOT equal to “#”.

$(“[href$=’.jpg’]”) select all elements with an href attribute that ends with “.jpg”.


jQuery CSS Selectors

jQuery CSS selectors can be used to change CSS properties for HTML elements.

The following example changes the background-color of all p elements to yellow:

Example

$(“p”).css(“background-color”,”yellow”);

Some More Examples

Syntax Description
$(this) Current HTML element
$(“p”) All <p> elements
$(“p.intro”) All <p> elements with
$(“p#intro”) All <p> elements with id=”intro”
$(“p#intro:first”) The first <p> element with id=”intro”
$(“.intro”) All elements with
$(“#intro”) The first element with id=”intro”
$(“ul li:first”) The first <li> element of the first <ul>
$(“ul li:first-child”) The first <li> element of every <ul>
$(“[href$=’.jpg’]”) All elements with an href attribute that ends with “.jpg”
$(“div#intro .head”) All elements with inside a <div> element with id=”intro”

Courtesy by  [http://www.w3schools.com]