Filling Dropdown in asp view in MVC3

If you are using asp views and need to fill a Drowpdown . The Below is the code for filling Drowpdown in asp view in MVC3.

Code in Model

using System;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Drawing.Text;
namespace DemoApp.Models
{
    public class DemoModel
    {      
        [Display(Name = "Role Name")]
        public int Role { get; set; }
 
        public IEnumerable RoleList
        {
            get { return new SelectList(getRole(), "Id", "Role"); }
        }
        public List getRole()
        {
            List Role = new List();
            SqlConnection connection = new SqlConnection
            (System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
            connection.Open();
            SqlCommand command = new SqlCommand("Select * from TBL_Role", connection);
            SqlDataReader rdr = command.ExecuteReader();
            while (rdr.Read())
            {
                Role.Add (new Role(){
                    id = int.Parse(rdr["id"].ToString()),
                    role= rdr["Role"].ToString()   
                }) ; 
            }
            connection.Close();
            return Role;
        }
    }
    public class Role
    {
        public int id { get; set; }
        public string role { get; set; }
    }
}

Code in Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DemoApp.Models;
namespace DemoApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            DemoApp.Models.DemoModel Model = new Models.DemoModel();
            return View(Model);
        }
        [HttpPost]
        public ActionResult Index(DemoModel Model)
        {
            string role = Request.Form["Role"];
            return View(Model);
        }
 
    }
}

Code in View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DemoApp.Models.DemoModel>" %>
 
<!DOCTYPE html>
 
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<%using ( Html.BeginForm("Index", "Home", FormMethod.Post)){ %>
<%: Html.LabelFor(m => m.Role)%>
<%: Html.DropDownList("Role", Model.RoleList)%>
<%: Html.ValidationMessageFor(m => m.Role)%>
<input type="submit" value="Submit" />
<% } %>
</div>
</body>
</html>
Rajat Jain
Latest posts by Rajat Jain (see all)
10 Comments
  1. Avatar web page
  2. Avatar webpage
  3. Avatar parajumpers kodiak dam
  4. Avatar website
  5. Avatar pjs jakke
  6. Avatar website
  7. Avatar parajumpers site officiel
  8. Avatar parajumpers jackor
  9. Avatar the north face himalayan parka
  10. Avatar Roderick

Leave a Reply