Thursday, 7 May 2015

Various way of Binding DropDownList in Mvc 4.0 with Sql Server Database


Various way of Binding DropDownList in Mvc with Sql Server Database

Note:  Here we will discuss, binding DropDownList in Mvc with five different ways

1.    Using Action Result
2.    Using Constructor
3.    Using Abstract Class
4.    Using Filter concept
5.    Using Custom Attribute

-- Sql Query………………………………………………….

use test
create table StateInfo
(
StateId int primary key,
StateName varchar(50) unique
)
insert  into  StateInfo values(1,'Uttar Pradesh')
insert  into  StateInfo values(2,'Madhya Pradesh')

select *  from StateInfo


Source Code  for  Index.cshtml……………………………

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using(Html.BeginForm())
{
<div>
@Html.DropDownList("State","--Select--")
<input type="submit" value="Save" />
</div>
}

</body>
</html>

We will take MvcApplication and add Controller which name is HomeControlle
                  
                Using Action Result …………………………………………………………….

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
// using this  namespace
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public class HomeController : Controller
{

DataClasses1DataContext database = new DataClasses1DataContext();

[HttpGet]
public ActionResult Index()
{
ViewBag.State = (from m in database.StateInfos select new SelectListItem { Text = m.StateName, Value=m.StateId.ToString() }).ToList();

// ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");
return View();
}

[HttpPost]
public ActionResult Index(StateInfo st)
{
ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");
return View();
}
}
}

Note: If you click the Save Button without calling both ViewBag.State on both[HttpGet] Index and [HttpPost] Index then you will get following type of error on your screen

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'State'.

                      Using Constructor…………………………………….

Note: if you are using this above concept with Constructor then you can simplify these two statement in a new one 
using System.Web.Mvc;
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public class HomeController : Controller
{
public HomeController()
{
ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");

}

DataClasses1DataContext database = new DataClasses1DataContext();

public ActionResult Index()
{
// ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");
return View();
}
[HttpPost]
public ActionResult Index(StateInfo st)
{

//ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");
return View();
}
}
}

Drawback: This state binding is only applied for  HomeContoller ,  if  you  want call same  logic in another  controller  then  we  have  to  call  but then define the   state binding  method again for  another  controller so this  drawback can be  remove  using  Abstract class concept

                             Using Abstract Class …………………………………….

Note: if you are  using this above concept with Abstract Class  then  you can implement this state  binding with any Controller when we had to  use  Constructor then we can only bind multiple Action   with  same  Controller  


Next step we will declare an abstract class in Controller which name StateBind

Code for StateBind.cs  ………………………………..

using System;
// using this name  space
using System.Web.Mvc;
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public abstract class StateBind:Controller
{
DataClasses1DataContext database = new DataClasses1DataContext();

public StateBind()
{

ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");

}

}
}

Code for HomeController.cs  ………………………………..

using System.Web.Mvc;
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public class HomeController :StateBind
{
DataClasses1DataContext database = new DataClasses1DataContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(StateInfo st)
{
return View();
}
}
}

Drawback:  here when we are working with above concept means (Abstract class) then you can call this state binding concept before Action but if you want to call after Action then we introduced a new concept Filter in Mvc

                          Using Filter Concept in Mvc …………………………………….


What is Filter:  Using filter you can put extra logic before or after action result calling

Types of Filter in Mvc


·         Action filter
·         Authorization filter
·         Authentication filter
·         Result filter
·         Exception filter

Here we are using Action Filter for above concept……………………..

//Called after the action method executes
  void OnActionExecuted(ActionExecutedContext filterContext);
// Called before an action method executes.
  void OnActionExecuting(ActionExecutingContext filterContext);

Example :

using System.Web.Mvc;
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public class HomeController :Controller,IActionFilter
{
DataClasses1DataContext database = new DataClasses1DataContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(StateInfo st)
{
return View();
}

void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{

}

void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");

}
}
}

Drawback: here we are declare filter in HomeController and this Controller contains multiple Action so filter is working for every Action, But  here  we want to call this filter  for particular Action so  here we will work  a  new concept  Custom  Attribute

                      Using Custom Attribute Concept in Mvc …………………………………….

We will declare class for Custom Attribute in Controller which name CustomState  inherited from abstract class ActionFilterAttribute ,you can see there are  four  virtual method  in following given image



Code for CustomState.cs………………………………….

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// using this namespace
using BindingConcept.Models;
using System.Web.Mvc;

namespace BindingConcept.Controllers
{

public class CustomState:ActionFilterAttribute
{

DataClasses1DataContext database = new DataClasses1DataContext();

public override void OnActionExecuted(ActionExecutedContext filterContext)
{

var v = filterContext.Controller.ViewBag;
v.State = new SelectList(database.StateInfos, "StateId", "StateName", "Select");
}
}
}

Code for HomeController.cs………………………………….

using System.Web.Mvc;
using BindingConcept.Models;

namespace BindingConcept.Controllers
{
public class HomeController :Controller
{

[CustomState]
public ActionResult Index()
{
return View();
}

[HttpPost]
[CustomState]
public ActionResult Index(StateInfo st)
{
return View();
}
}
}

Result





0 comments:

Post a Comment