標籤

ASP.NET MVC (29) Visual C# (15) JQuery (10) Plugins (8) JQuery Plugins (6) JavaScript (6) MySQL (5) CSS (4) LinQ (4) Mac OS (4) CentOS (3) Design Pattern (3) Entity Framework (3) IIS (3) Python (3) Windows (3) php (3) Docker (2) LAMP (2) SQL Server (2) WCF (2) .NET (1) .NET Core (1) AWS (1) Browser (1) GIS (1) IE (1) Internet Security (1) Linux (1) Platform (1) React (1) SEO (1) Testing (1) VMware (1) Windows 7 (1) cookie (1) curl (1) laravel (1) phpBB (1) session (1) 中古屋 (1) 透天 (1) 閒言閒語 (1) 面試 (1) 鳥松 (1)

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

沒有留言:

張貼留言