Category Archives: MVC

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

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

MVC4 Razor : How to get the value from view to controller

MVC4 Razor : How to get the value from view to controller ?

Explanation :

Here i explain how to get the value from html razor control (view) to controller

Code in View:

@using (Html.BeginForm())
{
@Html.TextBox(“txtCustomerName”)
<input type=”submit” value=”Send” />
}

Code in Controller

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Index1(FormCollection collection)
{
string customerName = collection[“txtCustomerName”].ToString();
return null;
}

Output :

After press send button the value will be catch in controller (as like below)

Note :
As above , we can get value of other control from the view to controller
1. [AcceptVerbs(HttpVerbs.Post)] , will do action when we use Html.BeginForm()
2. FormCollection : It provides to access  the values that were just posted to your page.