Thursday, 17 May 2012

example of dropdownlist in MVC

Code of the Controller

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

namespace MvcApplication36.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        DataClasses1DataContext o = new DataClasses1DataContext();
        public ActionResult Index()
        {
         
            List<SelectListItem> a = new List<SelectListItem>();
            var m = from x in o.EMPs select x;
            for (int i = 0; i < m.ToList().Count; i++)
                a.Add(new SelectListItem { Value = m.ToList()[i].EID.ToString(), Text = m.ToList()[i].NAME });
            ViewData["b"] = a;
            return View();

        }
        public ActionResult About()
        {
            return View();
        }
    }
}

Code of the view

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication36.Models.Test>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script>
    <script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(
function () {
    $('#btn').click(
    function () {
    alert($('#b').val())
    }
    )
}
)
    </script>
    <%Html.EnableClientValidation(); %>
    <%using (Html.BeginForm())
      { %>
    <form id="f">
    <table align="center">
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <%=Html.DropDownList("b","------Select------") %>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <input type="button" id="btn" value="Save" />
            </td>
        </tr>
    </table>
    </form>
    <%} %>
</asp:Content>

No comments:

Post a Comment