Bind DropDownList in MVC using ASP.Net

Write the below code on view on DDL.Aspx.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCTEST1.Models.DDLModel>" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>DDL</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <%:Html.DropDownListFor(m=>m.ddlStateId,Model.StateValue) %>

        <input id="Submit1" type="submit" value="submit" />

        <%:ViewData["X"] %>

    </div>

    </form>

</body>

</html>

Write the code on Model named DDLModel #region DDl public class DDLModel { public

string ddlStateId { get; set; } public string Name { get; set; } //DropDownList

Values public List<selectlistitem>

StateValue { get; set; } }

 

#endregion

On Controller write the below code.

DataRepository objRepository = new DataRepository();

public ActionResult DDL()

{

DDLModel objIndexViewModel = new DDLModel();

objIndexViewModel.StateValue = objRepository.GetStateName();

ViewData["Message"] = "Welcome to ASP.NET MVC!";

return View(objIndexViewModel);

}

To run you need to add you need to add a class in model folder named DataRepository.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using MVCTEST1.Models;

public class DataRepository

{

    //Create an instance of pankajEntities

    public pankajEntities entities = new pankajEntities();

    //Fetching data from table

    public List<SelectListItem> GetStateName()

    {

        var vStateName = (from User_Login in entities.User_Login

                          select new SelectListItem

                          {

                              Text = User_Login.Username,

                              Value = User_Login.Username

                          });

        return vStateName.ToList();

    }

}

Where pankajEntities in entity framework component.(You had to add it in model folder and connect to database table)

Ebook Download
View all
Learn
View all