Click here to Skip to main content
14,883,976 members
Please Sign up or sign in to vote.
3.72/5 (4 votes)
See more:
How to Bind Values To DropdownList in ASP.NET MVC?
Posted

In Action :

C#
public ActionResult Create()
    {
        var db = new DbDataContext();
        IEnumerable<SelectListItem> states = db.States.Select(p => new SelectListItem
        {
            Value = p.StateId.ToString(),
            Text = p.Name
        });
        ViewData["YourData"] = states;
        return View();
    } 



In View :

C#
<div class="editor-field">
                <%: Html.DropDownListFor(model => model.StateId, (IEnumerable<SelectListItem>)ViewData["YourData"])%>
                <%: Html.ValidationMessageFor(model => model.StateId) %>
            </div>
   
v3
Comments
Ur20 Mandaliya 19-Sep-12 4:27am
   
Developer Hemant Patel15,
Try it by your self.. If any problem is there than contact me..
First of all, there is no such thing as data binding in ASP.NET MVC. You have to pass select values from the controller to the model either using a view model, or via ViewBag (or ViewData if you still use MVC2). Here is a good "howto": http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists[^], but google can give you more.
And now with cascading.
There are several approaches, but these can be interesting:
1) If you know all your lists on the first render of your page, you can embed them in the view as JS arrays, and filter them on client side - this is not dynamic and can be a huge overhead.
2) Embed your "cascading" logic into the view: Simple Implementation of MVC Cascading Ajax Drop Down[^], but I don't recommend this, because it is not following the MVC concepts.
3) Using a Jquery, making an ajax callback to populate the second (and following) lists. I found a plugin, you might use: http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx[^] - I reccomend this approach, since you can dinamically calculate what elements to put into the list, and you don't need to refresh the page.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900