Sample Code:Bind the value to dropdownlist with model

Monday, 3 February 2014

Bind the value to dropdownlist with  model:


Controller:


        public ActionResult binddropdownwithmodel()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
            {
                Text = "item1",
                Value = "1"
            });
            items.Add(new SelectListItem
            {
                Text = "item2",
                Value = "2"
            });


            var model = new UserModel()
            {
                ListItems=items,
                SelectedItem=1
            };

            return View(model);

        }


Model:



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

namespace dropdownlistbind.Models
{
    public class UserModel
    {
        public List<SelectListItem> ListItems { get; set; }
        public int SelectedItem { get; set; }
    }
}


Create Strongly typed view:

   













































View:

@model dropdownlistbind.Models.UserModel

@{
    ViewBag.Title = "binddropdownwithmodel";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>binddropdownwithmodel</h2>

<style type="text/css"> 
        .DropDownListCssClass 
        { 
            color:Snow; 
            background-color:DarkOrchid; 
            font-family:Comic Sans MS; 
            font-size:large; 
            font-style:italic; 
            } 
</style>
<br />
<br />
@Html.DropDownList("SelectedItems", Model.ListItems, new { @class = "DropDownListCssClass" })


ScreenShot:






Render the html:

<select id="SelectedItems" class="DropDownListCssClass" name="SelectedItems">


Conclusion:

   Bind the values to dropdownlist from the model.