Sunday, 11 May 2014

Action Filters in MVC 4


Action Filters are attributes that can be applied either on a controller action method or on a controller. When applied at the controller level, they are applicable for all action methods with in that controller. Action Filters allow us to add, pre and post processing logic to an action method. This means they allow us to modify the way in which the action is executed.

Types of Action Filters

Authorize
ChildActionOnly
HandleError
OutputCache
RequireHttps
ValidateInput

Validate AntiForgeryToken

tags:action filters in mvc,action filters in mvc 5,filters in mvc ,autorize filters in asp.net mvc ,filters  in asp.net mvc 5, action filters in asp.net mvc 4,filters in asp.net mvc 6,handle error filter in asp.net mvc,validate anti forgery token in asp.net mvc 5,validate anti forgery token in asp.net mvc 6,validate anti forgery token in asp.net mvc 4,action filters in asp.net mvc 5,action filters in asp.net mvc 5,action filters in asp.net mvc 4,types of action filters in asp.net mvc 5,types of action filters in asp.net mvc 4,types of action filters in asp.net mvc 6

Filters in MVC 4

Authorization Filters :

These filters implement and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

Action Filters :

Action Filters are attributes that can be applied either on a controller action method or on a controller. When applied at the controller level, they are applicable for all action methods with in that controller. Action Filters allow us to add, pre and post processing logic to an action method. This means they allow us to modify the way in which the action is executed.

Result Filters :

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

Exception Filters :


Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.

tags: filters in mvc 4,filters in mvc 5,action filters in mvc 4,action filters in mvc4,filters resultfilers,customfilters,actionfilters,filters in mvc,mvc fiulters ,actionfilters in mvc,actionfilters in mvc 5,filters in mvc ,authorize filters,resultfilters,outputcache filters in asp.netmvc ,filters  in asp.net mvc 5,action filters in asp.net mvc 4,filters in asp.net mvc 6,handle error filter in asp.net mvc,validate anti forgery token in asp.net mvc 5,validate anti forgery token in asp.net mvc 6,validate anti forgery token in asp.net mvc 4,action filters in asp.net mvc 5,action filters in asp.net mvc 5,action filters in asp.net mvc 4,types of action filters in asp.net mvc 5,types of action filters in asp.net mvc 4,types of action filters in asp.net mvc 6

Cascading DropdownList in mVC 4

Here  I am going to explain cascading dropdown list In mvc  4. I want to populate countries in one dropdown and states in one dropdown list , based on the country selection it will populate the states in another dropdown list.

Go to Visual studio 2012=>New Project=>Give the name as MvcCascading
Add one model  class to Model’s folder name it as countries and add 2 properties to this model

public class Countries
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }

In this article I won’t use database. I added countries to list in controller itself .In controller add another method name as Countries.

Add  using MvcCascading.Models; 

In controller write the code like below
  public ActionResult Countries()
        {
            List<Countries> objcounties = new List<Models.Countries>();
            objcounties.Add(new Countries { CountryId = 1, CountryName = "India" });
            objcounties.Add(new Countries { CountryId = 2, CountryName = "Japan" });
            objcounties.Add(new Countries { CountryId = 3, CountryName = "France" });
            ViewBag.counties = new SelectList(objcounties, "CountryId", "CountryName");
            return View();         
        }
We pass the list of countries to view through the viewbag.
Add View to Countries Action method and write the below  code in View
@{
    ViewBag.Title = "Countries";
}

<h2>Countries</h2>
<br /><br />
@Html.DropDownList("counties", "select Country")
Here countries in Dropdown is Viewbag.Countries. we have to give Viewbag name  


Now run the application and see the output as following


Now I add one more dropdownlist for states.
Add one more model class to Model’s folder name it as States and the following properties.
public class States
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public int CountryId { get; set; }     
    }

Now in controller add one more action method name it as States
In states action method pass id and  return type is jsonresult because we send the data as json format to populate dropdown and I write one linq query for get the states based on country id ,here we go

  public JsonResult States(int id)
        {
            List<States> objstates = new List<Models.States>();
            objstates.Add(new States { CountryId = 1, StateName = "Hyderabad" });
            objstates.Add(new States { CountryId = 1, StateName = "Chennai" });
            objstates.Add(new States { CountryId = 2, StateName = "JapanState1" });
            objstates.Add(new States { CountryId = 2, StateName = "JapanState2" });
            objstates.Add(new States { CountryId = 3, StateName = "FranceState1" });
            objstates.Add(new States { CountryId = 3, StateName = "FranceState2" });

            var state = from s in objstates where s.CountryId == id select s;
            return Json(new SelectList(state.ToArray(), "CountryId", "StateName"),
                JsonRequestBehavior.AllowGet);           
        }



Now in Countries.cshtml chage the code like below
<h2>Countries</h2>
<br /><br />
@Html.DropDownList("counties", "select Country")
<br /><br />
<select id="States"></select>


Add following script and use $.getJson method to populate the dropdown
<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script>
    $(document).ready(function () {   
        $("#counties").change(function () {
            $.getJSON('/Home/States/' + $("#counties").val(), function (data) {
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) {                  
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $("#States").html(items);
            });
        });
    });

</script>

Finally the countries.cshtml is like this
@{
    ViewBag.Title = "Countries";
}

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script>
    $(document).ready(function () {   
        $("#counties").change(function () {
            $.getJSON('/Home/States/' + $("#counties").val(), function (data) {
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) {                  
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $("#States").html(items);
            });
        });
    });

</script>

<h2>Countries</h2>
<br /><br />
@Html.DropDownList("counties", "select Country")
<br /><br />
<select id="States"></select>


Now run the application and see the following output.


Tags: cascading dropdown list in mvc 4, cascading dropdown list in mvc 3,

cascading dropdown list in mvc 5,counties states dropdownlist in mvc 4,2 dropdowns in mvc 4,two dropdowns in mvc4

Tuesday, 21 January 2014

Models in MVC 4

In this article i am going to explain models in mvc.we want to retrieve an employee information from Employee table and display it as shown below.




 To encapsulate employee information I need to have an employee model class. let’s add employee model class to mvc project. Go to Models folder right click on it and change class name  as Employee and click on add. Write below code in Employee Model Class

public class Employee
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
    }


Let’s add another controller name it as Employee, actually we retrieve the employee information from the Database, but for now I am going to hard coded the employee information with in the controller.
I need to find the Employee class with in the controller but I didn’t find, so add MvcDemoApps.Models
 Here Mvcdemoapps is application name.



We need to add a view which can present the employee information to the end user. Right click on Controller action method and select add view. check the create a strongly-typed view, select Model class Employee with in dropdownlist but there is no Employee class for that build the application now it appears in Dropdownlist select Employee Model class and click on Add.

Lets change code in the Details View
@model MvcDemoApps.Models.Employee

@{
    ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>
<table>
<tr>
<td><b>Employee Id</b></td>
<td>@Model.EmpId</td>
</tr>
<tr>
<td><b>Employee Name</b></td>
<td>@Model.Name</td>
</tr>
<tr>
<td><b>Gender</b></td>
<td>@Model.City</td>
</tr>
<tr>
<td><b>City</b></td>
<td>@Model.City</td>
</tr>
</table>

Now run the application (give controller name and action method name in the controller).
You will get following error


Because we didn’t pass employee object to  view. Let’s pass employee object to view
  public ActionResult Details()
        {
            Employee objemployee = new Employee()
            {
                EmpId=200,
                Name="SriRama",
                Gender="Male",
                City="Hyderabad"
            };
            return View(objemployee);
        }
Now run the application and we get the following output.
 tags:Models in Mvc,:Models in Mvc 4,:Models in Mvc 3,:Models in asp.netMvc,:Models,:Models in Mvc