2011年4月21日星期四

[ASP.NET MVC] 如何在View中使用強型別DropDownListFor

How to use the strongly type "DropDownListFor" in View in ASP.NET MVC.
===============================================================
First, Assume I have two tables "Person,Weapon" both have relationship:

[Person]
{
    PersonID
    WeaponID
}

[Weapon]
{
    WeaponID
    WeaponName
}

---
OK, now I want to show the information of all the Person in database. I should write:
using (Entites db = new Entites())
            {
                var result = (from s in db.Person.Include("Weapon") select s).ToList();
                return View(result);
            }
            return View();


View:
<% foreach (var item in Model) { %>
        <%: Html.DropDownListFor(s=>s.Person.Where(a=>a.WeaponID == item.WeaponID).WeaponID , 
    new SelectList(MyApplication.Models.DropDownList.GetDropDownList(), "Value", "Text", item.WeaponID )%>    
><% } %>



Now we should write the class DropDownList with namespace MyApplication.Models:
class DropDownList
    {
        public List GetDropDownList()
        {
            List result = new List();
            result.Add(new System.Web.Mvc.SelectListItem
            {
                Value = "1",
                Text = "Apple"
            });
            result.Add(new System.Web.Mvc.SelectListItem
            {
                Value = "2",
                Text = "Milk"
            });
            return result;
        }
    }


In fact, GetDropDownList() Method can access the data via Weapon table in our database.

Reference:http://stackoverflow.com/questions/4312925/asp-net-mvc-dropdownlistfor-or-dropdownlist-with-strongly-typed-viewmodel

weak-type: http://ittecture.wordpress.com/2009/05/10/tip-of-the-day-208-asp-net-mvc-populating-dropdownlists-using-linq-to-sql/

Some discussion: http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value

沒有留言:

張貼留言