MCV Fill DropDownBox !!!

Let’s start with an example how to fill dropdownbox with
a very very simple example of (Employee Grade List) as I believe

– “Solution can be described in few words”

# Fill Dropdownbox
Key Note: We need SelectListItem class of System.Web.Mvc

Employee Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
     public class EmployeeController : Controller
     {
          public ActionResult index()
          {
               var Grade = new List();
               Grade.Add(new SelectListItem() { Text = "A", Value = "1" });
               Grade.Add(new SelectListItem() { Text = "B", Value = "2" });
               Grade.Add(new SelectListItem() { Text = "C", Value = "3" });
               Grade.Add(new SelectListItem() { Text = "D", Value = "4" });
               Grade.Add(new SelectListItem() { Text = "E", Value = "5" });
               Grade.Add(new SelectListItem() { Text = "F", Value = "6" });
               ViewBag.Grade = Grade;
               return View();
          }
     }
}

Employee Index View (index.cshtml):
Employee<br/>
Grade: @Html.DropDownList("Grade")

Step1

# Set Default Text (Note: Just add default text for optionLable)

Employee<br/>
Grade: @Html.DropDownList("Grade","Select Grade")

Step2

# Select value for edit before update (Note: Just add selected true for SelectListItem)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
   public class EmployeeController : Controller
   {
     public ActionResult index()
     {
       var Grade = new List<SelectListItem>();
       Grade.Add(new SelectListItem() { Text = "A", Value = "1" });
       Grade.Add(new SelectListItem() { Text = "B", Value = "2" });
       Grade.Add(new SelectListItem() { Text = "C", Value = "3" });
       Grade.Add(new SelectListItem() { Text = "D", Value = "4" });
       Grade.Add(new SelectListItem() { Text = "E", Value = "5", Selected=true });  // This option will be selected by default
       Grade.Add(new SelectListItem() { Text = "F", Value = "6" });
       ViewBag.Grade = Grade;
       return View();
     }
   }
}

Step3

Note: Grade system creates division among people !!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s