Saturday 18 March 2017

Bind DropDownList Using ViewBag In ASP.NET MVC

Bind data using ViewBag

Description:

In this example we explain that how to bind dropdown List using ViewBag in Asp.Net MVC.sometime we need to bind DropdownList using ViewBag property in MVC.

Suppose you have list of temporary country and you want to bind it in DropdownList control in MVC then ViewBag is the best way to bind all country in DropdownList in MVC.

Below is the code to demonstrate how to bind dropdownlist using ViewBag in asp.net MVC.
Controller:

using System.Collections.Generic;
using System.Web.Mvc;

namespace BindDropDownlistUsingViewBag.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //Creating generic list
            List<SelectListItem> ObjCountryList = new List<SelectListItem>()
            {
                new SelectListItem { Text = "India", Value = "1" },
                new SelectListItem { Text = "USA", Value = "2" },
                new SelectListItem { Text = "UK", Value = "3" },
                new SelectListItem { Text = "China", Value = "4" },

            };
            //Assigning generic list to ViewBag
            ViewBag.Country = ObjCountryList;

            return View();
        }
    }
}


View:

@{
    ViewBag.Title = "http://aspsolutionkirit.blogspot.com";
}
<div class="form-horizontal">
    <div class="col-md-12" style="margin-top:20px">
 @Html.DropDownList("ObjCountryList", (IEnumerable<SelectListItem>)ViewBag.Country, new { id = "ddlCountry", @class = "form-control" })
    </div>
</div>



This entry was posted in :

0 comments:

Post a Comment