Skip to main content

binding dropdownlist in .net mvc razor by viewbag, model and jquery - 3 ways

There is a lot of ways to bind dropdownlist in asp.net mvc (mvc3, mvc4 or later razor syntax .cshtml) and maintaining dropdownlist state during postback some of them given below -
  • Use viewbag property.
  • Through view model.
  • Use jquery .ajax i.e. asynchronous post back at selected index change of another dropdownlist.

I am taking a simple example to explain this, here is three dropdownlist that is for state, correspondence city of the state and correspondence area of that city, city and area bind at runtime as per state dropdownlist , city dropdownlist selection change respectively

binding dropdownlist in .net mvc razor by viewbag, model and jquery demo

Fill Data To Dropdownlist Using ViewBag Property

Use viewbag property as list container pass your list into a dynamic property of viewbag and use it into view part, first time (Get Request) city and area dropdownlist should be blank so use empty list for blank dropdownlist as below for binding city and area list during postback request use jquery part as given in the end of the post.
Well for maintating the state during post back just pass FormCollection class as parameter of post postyourad action and rest all the thing model binder will handle, you can also use like this
public ActionResult postyourad(string istateid,string icityid,string iareaid) model binder automatic bind these value with posted form data collection

Controller class ActionResult -
[HttpGet]
public ActionResult postyourad()
{
    ViewBag.stateList = getState();
    ViewBag.cityList = new List<SelectListItem> { };  //blank dropdownlist
    ViewBag.areaList = new List<SelectListItem> { };  //blank no item
     
    return View( );
}

//State management during postback bind again
[HttpPost]
public ActionResult postyourad(FormCollection value)
{
    ViewBag.stateList = getState(value["istateid"]);
    ViewBag.cityList = getCity(value["istateid"], value["icityid"]);
    ViewBag.areaList = getArea(value["istateid"], value["icityid"], value["iareaid"]);

    return View();

}

View page .cshtml -
@{
    ViewBag.Title = "dropdownlist bind demo with viewbag";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm()) {

    @Html.DropDownList("istateid", (SelectList)ViewBag.stateList, "--Choose Your State--")
    @Html.DropDownList("icityid", (IEnumerable<SelectListItem>)ViewBag.cityList, "--Choose Your City--")
    @Html.DropDownList("iareaid", (IEnumerable<SelectListItem>)ViewBag.areaList, "--Choose Your Area--")
  
    <input type="submit" value="submit" />

}

Bind Dropdownlist Using View Model 

below is the example of binding dropdownlist through view model named mydropdownlist it have three property and three method return as SelectList type, just pass mydropdownlist class object to view and bind as given in view part below.
For maintaining state during postback pass mydropdownlist as parameter then model binder automatic bind posted data into it (model binder check name of property and name of the field of posted form data and bind accordingly) or you can use FormCollection Class as above.

binding dropdownlist in .net mvc razor by viewbag, model and jquery structure

Controller Class ActionResult -
[HttpGet]
public ActionResult postyourad()
{
    return View(new mydropdownlist());
}

//State management during postback model binder automatic bind the propery of dropdownlist
[HttpPost]
public ActionResult postyourad(mydropdownlist ddlListPostData)
{
    //mydropdownlist ddlList = new mydropdownlist() { istateid = ddlListPostData.istateid, icityid = ddlListPostData.icityid, iareaid = ddlListPostData.iareaid };
    return View(ddlListPostData);

}

View part .cshtml -
@model ECommerce.Models.mydropdownlist
@{
    ViewBag.Title = "dropdownlist bind demo with model";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm()) {
    @Html.DropDownListFor(x => x.istateid, Model.getState() , "--Choose Your State--")
    @Html.DropDownListFor(x => x.icityid, Model.getCity(), "--Choose Your City--")
    @Html.DropDownListFor(x => x.iareaid, Model.getArea(),"--Choose Your Area--")
  
    <input type="submit" value="submit" />
}

View Model -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace ECommerce.Models
{
public class mydropdownlist
{
 MyDbContext _db = null;
 public mydropdownlist() { _db = new MyDbContext(); }

 [Required]
 public virtual string iareaid { get; set; }
 [Required]
 public virtual string icityid { get; set; }
 [Required]
 public virtual string istateid { get; set; }



 public SelectList getState()
 {
  IEnumerable<SelectListItem> stateList = (from m in _db.mstrstates where m.bstatus == true select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vstate, Value = m.istateid.ToString() });
  return new SelectList(stateList, "Value", "Text", istateid);
 }


 public SelectList getCity()
 {
  IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
  if (!string.IsNullOrEmpty(istateid))
  {
    int _stateId = Convert.ToInt32(istateid);
    cityList = (from m in _db.mstrcities where m.bstatus == true && m.istateid == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vcity, Value = m.icityid.ToString() });
  }
  return new SelectList(cityList, "Value", "Text", icityid);
 }


 public SelectList getArea()
 {
   IEnumerable<SelectListItem> areaList = new List<SelectListItem>();
   if (!string.IsNullOrEmpty(istateid) && !string.IsNullOrEmpty(icityid))
   {
    int _cityId = Convert.ToInt32(icityid);
    int _stateId = Convert.ToInt32(istateid);
    areaList = (from m in _db.mstrareas join p in _db.mstrcities on m.icityid equals p.icityid where m.bstatus == true && m.icityid == _cityId && p.istateid == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vareaname, Value = m.iareaid.ToString() });
   }
   return new SelectList(areaList, "Value", "Text", iareaid);
  }
 }
}

Bind Data To Dropdownlist using jquery .ajax post in selection change event

If you want to bind dropdownlist according to posted data during postback (asynchronously) in selected item change event of another dropdownlist then you can do this through jquery .ajax method and through JsonResult (JsonResult - Serializes a given ViewData object to JSON format) as given below -

View part .cshtml -
$("#istateid").change(function () {
 $.ajax({
   type: "POST",
   url: '@Url.Action("getCityJson", "PostAd")',
   data: { stateId: $("#istateid > option:selected").attr("value") },
   success: function (data) {
       var items = [];
       items.push("<option>--Choose Your Area--</option>");
       $.each(data, function () {
           items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
       });
       $("#icityid").html(items.join(' '));
   }
 })
});

$("#icityid").change(function () {
   $.ajax({
       type:"POST",
       url: '@Url.Action("getAreaJson", "PostAd")',
       data: { cityId: $("#icityid > option:selected").attr("value"), stateId: $("#istateid > option:selected").attr("value") },
       success: function (data) {
       var items = [];
       items.push("<option>--Choose Your Area--</option>");
       $.each(data, function () {
           items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
       });
       $("#iareaid").html(items.join(' '));
   }
 })

});


Controller Class ActionResult -
[HttpPost]
public JsonResult getStateJson(string selectStateId = null)
{
    return Json(getState(selectStateId));
}
public SelectList getState(string selectStateId = null)
{
    IEnumerable<SelectListItem> stateList = (from m in _db.mstrstates where m.bstatus == true select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vstate, Value = m.istateid.ToString() });
    return new SelectList(stateList, "Value", "Text", selectStateId);

}

[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId=null)
{
    return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
    IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
    if (!string.IsNullOrEmpty(stateId))
    {
        int _stateId = Convert.ToInt32(stateId);
        cityList = (from m in _db.mstrcities where m.bstatus == true && m.istateid == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vcity, Value = m.icityid.ToString() });
    }
    return new SelectList(cityList, "Value", "Text", selectCityId);

}

[HttpPost]
public JsonResult getAreaJson(string stateId, string cityId, string selectAreaId = null)
{
    return Json(getArea(stateId, cityId, selectAreaId));
}
public SelectList getArea(string stateId, string cityId, string selectAreaId = null)
{
    IEnumerable<SelectListItem> areaList = new List<SelectListItem>();
    if (!string.IsNullOrEmpty(stateId) && !string.IsNullOrEmpty(cityId))
    {
        int _cityId = Convert.ToInt32(cityId);
        int _stateId = Convert.ToInt32(stateId);
        areaList = (from m in _db.mstrareas join p in _db.mstrcities on m.icityid equals p.icityid where m.bstatus == true && m.icityid == _cityId && p.istateid == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vareaname, Value = m.iareaid.ToString() });
    }
    return new SelectList(areaList, "Value", "Text", selectAreaId);

}


Popular posts from this blog

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net. Following code demonstrating the various ways of implementation.

Regular expression for alphanumeric with space in asp.net c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax

Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

How to validate dropdownlist in JavaScript

In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is "-Select-" just like given below and we have to validate that at least one item is selected excluding default i.e "-Select-".