All posts by Thiyagu

How to use cascading DropDown in MVC Razor

How to use cascading DropDown in MVC Razor

Model

namespace RegistrationForm.Models
{
public class UserDetailModel
{
[Display(Name = "CountryDetail")] public List<Country> CountryDetail; [Display(Name = "selectedcountry")] public string SelectedCountry { get; set; } [Display(Name = "stateDetail")] public List<State> StateDetail { get; set; } } public class Country { public int CountryId { get; set; } public string CountryName { get; set; } } public class State { public int StateId { get; set; } public string StateName { get; set; } } }

Controller:

public class GettingTextInDDLController : Controller
{
public ActionResult Index()
{
var obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  "INDIA" },
new Country() { CountryId = 2, CountryName= "US" },
new Country() { CountryId = 3, CountryName= "Russia" },
new Country() { CountryId = 4, CountryName= "UK" }
};

return View(obj);
}
public ActionResult FirstDdl(string selectedCountry)
{
var obj = new UserDetailModel();
if (selectedCountry == "INDIA")
{
obj.StateDetail = new List<State>()
{
new State() {StateId = 1, StateName = "Tamil Nadu"},
new State() {StateId = 2, StateName = "Karnataka"},
new State() {StateId = 3, StateName = "Delhi"},
new State() {StateId = 4, StateName = "J&K"}

};
}
else
{
//.... Bind states for other countries
obj.StateDetail = new List<State>()
{
new State() {StateId = 1, StateName = "Others"},
};
}

return Json(obj);
}
}

View  

use @model RegistrationForm.Models.UserDetailModel in the first line of view

<script type="text/javascript">
function ddListChange() {
$.ajax({
url: '@Url.Action("FirstDdl", "GettingTextInDDL")',
data: { selectedCountry: $('#SelectedCountry option:selected').text() },
cache: false,
type: "POST",
success: function (data) {
var parsedJsonData = data.StateDetail.length;
var state = "<option value=`0`>Select City</option>";
for (var x = 0; x < parsedJsonData; x++) {
state += "<option value=" + data.StateDetail[x]["StateId"] + ">" + data.StateDetail[x]["StateName"] + "</option>";
}
$('#ddlstate').html(state).show();
},
error: function (reponse) { alert("error : " + reponse); }
});
}
</script>

<table>
<tr>
<td id="tdcountry">
@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail, "CountryId", "CountryName"),
new
{
onchange = "ddListChange()"
})
</td>
</tr>
<tr>
<td id="tdstate">
<select id="ddlstate" name="ddlstate" style="width: 200px">
<option>Select Country</option>
</select>
</td>
</tr>
</table>

Output

Before Selecting Country:

cascadingddl 1

After Selecting it will populate list of states belong to Country India

Confirmation message after clicking the ActionLink in MVC

In many scenario, it necessary to pop up the confirm alert box while deleting ,saving and editing  information in Asp .Net MVC application. So let us discuss about how can we achieve using JQuery code .

Controller

Create simple controller and generating view based on the controller as shown below.

View (index)

As shown below code, we had created ConfirmationDialog function using javascript to show the popup with alert message. Next creating a AcionLink control which will show the popup by calling the javascript method in the onclick event.

<script type="text/javascript">
function ConfirmationDialog() {
if(confirm("Are you sure to continue?"))
return true;
else
return false;
}
</script>

@Html.ActionLink("Click to Confirm", "Confirmation", null, new { onclick = "return ConfirmationDialog()" })

OUTPUT:

If you click ok, it will redirect to the Confirmation view

store array in viewbag and retrieving in the view

In this post, we will discuss about how to store the array in view bag and how to use them in view.

Controller

A simple Controller action which store the string array in the ViewBag and return to the view.

public ActionResult Index()
{
string[] Countries = {“India”, “US”,”Nepal” };
ViewBag.Countries = Countries;
return View();
}

View

<h2>List Of Cities</h2>
@foreach (string city in ViewBag.Countries) {
<li>@city
</li>
}

OUTPUT :

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:

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