All posts by Thiyagu

Validation in MVC4 Razor with the Data Annotation Validators in “MODEL”

Data Annotation

Data validation play major role when developing web application. In Asp.net MVC, we can easily implement validation to application by using Data Annotation attribute to model. Data Annotation attribute classes are present in System.ComponentModel. DataAnnotations namespace. It is a common validation attributes which extend the built-in ASP.NET DataAnnotations (Required, Range, RegularExpression, StringLength etc.,). ASP.NET MVC uses jquery unobtrusive validation to perform client side validation.

MODEL

using System.ComponentModel.DataAnnotations;
namespace validation.Models
{
public class ValidationModel
{
[Required] [Display(Name = "User name")] [StringLength(20,ErrorMessage = "Name not be exceed 20 char")] public string Name { get; set; } [Required(ErrorMessage = "Email_id must not be empty")] [RegularExpression(".+\@.+\..+", ErrorMessage = "Please Enter valid mail id")] public string Email { get; set; } [Required(ErrorMessage = "Please enter phone number")] [RegularExpression(@"^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Enter valid number")] public string Phone { get; set; } [Required(ErrorMessage = "Please enter your address")] public string Address { get; set; } [Range(0,120,ErrorMessage = "Please enter between 0 to 120")] public string Age { get; set; } } }

View

@model validation.Models.ValidationModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@using (Html.BeginForm())
{
@Html.ValidationSummary(false)
<table>
<tr> <td>
Your Name: @Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</td> </tr>
<tr> <td>
Your Age: @Html.TextBoxFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</td></tr>
<tr> <td>
Your Email: @Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</td></tr>
<tr><td>
Your Phone: @Html.TextBoxFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</td></tr>
<tr><td>
Your Address: @Html.TextBoxFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</td></tr>
<tr><td>
<input type="submit" value="Register Me" />
</td></tr>
</table>
}

OUTPUT:

Validation using Data Annotation Validator 1 - MVC - dotnet-helpers

Below output shows the Email validation and Range validation

NOTE :

Validation for password comparsion

[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]

MVC Razor : Difference between @Html.Partial() and Html.RenderPartial()

Difference between @Html.Partial() and Html.RenderPartial()

  • Html.Partial returns a string, Html.RenderPartial returns void.
  • We can store the output of Html.Partial in a variable/able to return from function.
  • In Html.RenderPartial, we can’t result void.(ie.,directly writing to the output stream so it was bit faster than html.partial())

Example :

If want to refere partial view inside the shared, then it will

@{ Html.RenderPartial(“_testPartial”);}

If want to refere partial view inside the view, then it will be

@Html.Partial(“../Home/testContentPartial”)

 

Partial View in MVC

Introduction to Partial View in MVC

Partial view is special view which renders a portion of view content. Partial can be reusable in multiple views. It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view. A partial view is like as user control in Asp.Net Web forms that is used for code re-usability.Partial views helps us to reduce code duplication. The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view so that partial view can access the data of the parent view.

In simple , partial view is a child-view/sub-view that you can include in a parent view

Step 1 :

Creating a MVC project by clicking New à Project

Step 2:

After selecting the project , and select visual c# with ASP .NET MVC 4 Web Application and change the name of the project and location then click ok button

Step 3:

After  clicking ok it will open new wizard for choosing type of the application and engine. In that choose internet application and razor engine(what ever engine u going to use) and click ok

Step 4:

After clicking ok, the solution will structured like below screen

Step 5:

Now we going to create partial view to the default view(ie., index). Right click the Home folder as like below image and choose view option

Step 6:

After selecting view it will move to next wizard. In that choose Engin type and name of the partial view and click the “Create as a partial view” and click add button

Step 7:

Create sample paragraph inside the partial view and save

Step 8:

Call the partial view in the index by using @Html.Partial(“HeaderPartial”). “HeaderPartial” be the name of the partial view

Step 9:

Press F5 and see the content of partial view in the index view

Difference between ‘return false;’ and ‘e.preventDefault();

Difference between ‘return false;’ and ‘e.preventDefault();

  •  `e.preventDefault()` which will prevent the default event from occurring, but will continue the event flow (ie., next line of code in the function)
  •   return false will always had to go at the end of your function, or at the end where no further execution was needed.

HTML :

<div id=”preventDef”>
<a href=”#”>Pls Click Here!</a>
</div>

<div id=”returnFalse”>
<a href=”#”>Pls Click Here!</a>
</div>

JQUERY

$(“#preventDef a”).click(function(e) {
e.preventDefault();
$(this).hide();
});

$(“#returnFalse a”).click(function(e) {
return false;$(this).hide();
$(this).hide();
});

OUTPUT

Explanation :
If you click first link… it will hide , because it will not fire particular event to fire but it will continue with next line in the function

Bur if you click on second link, it will not hide because it will move the end of the loop/function

How to close the div popup/any Element while clicking outside of the popup

How to close the div popup/any Element while clicking outside of the popup

JQUERY

$(document).mouseup(function(e)
{
var container = $(“#divPatientDetail”);
if (container.has(e.target).length === 0)
{
container.hide();
}

});

Explanation:

var container = $(“#divPatientDetail”); — Assigning the selector to the variable

container.hide(); — After checking the condition , it hide the selector element

Note :

It will not hide while clicking inside of the div/Element

Implementing Globalization , Localization in MVC Razor

Implementing Globalization  , Localization in MVC Razor

 Short introduction:

Globalization  :  Tthe process of designing and developing application that functions in multiple cultures/locales.
(Adapting a global product for a multiple language)
Localization   :  The process of adapting a particular language. ie., which is comfortable to use in the target country.

In this post let we see how we implement Localization

Step 1 :   Add resource file to the application as show in below

Step 2 : Open Resources.resx fils and enter the key and value as like below screen

Note :  while saving the resource file ,we want to set the access specifier to access the resource name in the view

Step 3 :  Add the following code in the view

               View : Include reference on the top of the view page

@using MVCRazor.Properties
<div> @Resources.sampletext</div>

Step 4 : Run the application

Description :

1 ) @using MVCRazor.Properties  : importing the reference to the view

2) @Resources.sampletext :  @Resources is a name of the resource and sampletext be a key of the resource file

3) At runtime it will display the equlant value match for the key

MVC Razor : How to call controller from html radio button click event using Jquery

In this post we will discuss about how to call the controller from the radio button click event using jquery.

HTML :

<div id=”radio”>
<input type=”radio” id=”Isactive” name=”Isactive” value=”1″ >Yes</input >
<input type=”radio” id=”Isactive” name=”Isactive” value=”0″ >No</input >
</div>

JQUERY :

$(document).ready(function () {
$(‘input[type=radio]’).live(‘change’, function()
{
alert($(this).val());
window.location = ‘@Url.Action(“UserDetail”, “AllUserDetail”)’;
});

});

Controller : AllUserDetailController

public ActionResult UserDetail()
{
//Perform action here
}

Explanation:

  • window.location = ‘@Url.Action(“UserDetail”, “AllUserDetail”)’;

UserDetail : This will be the name of the action
AllUserDetail : This will be the name of the controller.

 

 

MVC – Passing JSON data from controller to the view

Passing JSON data from controller to the view

UserDetailController.cs

[HttpPost]
[ValidateInput(false)]
public JsonResult FetchUserDetailsByid(string userID)
{
List<UserDetailByID>  userDetailollection;
try
{
//return the User Details List
userDetailollection = new GetUserDetailsByidModel().FetchUserDetailByid(UserID));
}
catch (Exception ex)
{

throw ex;
}
var jsonSerializer = new JavaScriptSerializer();
string output = jsonSerializer.Serialize(userDetailollection );
return Json(new
{
output
}, JsonRequestBehavior.AllowGet);
}

Included Namespace:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Script.Serialization;

View (JQUERY)

$.ajax({url: “@Url.Action(“FetchUserDetailsByid”, “UserDetail”)”,
data: “{ ‘userID’: ‘” + userID + “‘ }”,
dataType: “json”,
type: “POST”,
contentType: “application/json; charset=utf-8”,
success: function(data)
{
//Converting JSON String to JSON Object
var jsonObject = $.parseJSON(data.output);
if (parseInt(jsonObject.length) > 0)
{
alert( jsonObject[0].UserName);
}
},
error: function(result) {
alert(“Error”);
}

Note :

1.  URL  “FetchUserDetailsByid” be the name of the method
             “UserDetail” be the name of the controller

2. “var jsonObject = $.parseJSON(data.output);” is used to converting
         json string to object

How to split the attribut “class” name in the html element

How to split the attribute “class” name  in the html element

HTML :

<div id=”divUserDetails” class=”red”>

JQEURY :

$(document).on(“click”, “#divUserDetails”, function()
{
var userColor = $(this).attr(‘class’) == null ? “No User Color Found” : $(this).attr(‘class’);
alert(userColor );
}

Output

Here is the output