在asp.net mvc 2.0中将数据从数据库绑定到DropDownListFor

时间:2012-07-06 11:56:57

标签: asp.net-mvc-2

我是asp.net mvc 2.0的新手,我试图搜索这篇文章,但仍然无法得到我想要的答案。

我有一个表单可以为每个员工分配角色。所以我创建了一个表单,我可以输入员工的姓名并选择他们所在的角色。该角色来自表格角色。我使用linq to sql从表Role查询RoleName和RoleID,并希望在我的视图中将它绑定到DropDownListFor。

我有一个型号:

public class UserModels
{

   public string name { get; set; }
   public string role { get; set; }

}

这就是我在控制器中所做的:

[HttpPost]
public ActionResult UserMaintenance(FormCollection frm)
{
if (ModelState.IsValid)
{
    EMP_DBSEntities context = new EMP_DBSEntities();
    tblUserLogin user = new tblUserLogin();
    user.UserName = frm["userLogin"].ToString();

    IEnumerable<SelectListItem> role_list = context.tblRoles.Select(d => new SelectListItem
    {
        Value = d.RoleID.ToString(),
        Text = d.RoleName
    });


    context.AddTotblUserLogins(user);
    context.SaveChanges();
    return View();
}
else
{
    return View();
}
}

任何人都可以告诉我如何将role_list绑定到我的DropDownListFor&lt;&gt;在我看来。

感谢。

1 个答案:

答案 0 :(得分:1)

要创建下拉列表,您需要具有2个属性的视图模型:包含所选值的标量属性和包含可用选项的集合属性。

因此,在ASP.NET MVC中始终通过编写视图模型开始:

public class UserRoleViewModel
{
    [DisplayName("name")]
    public string EmployeeName { get; set; }

    [DisplayName("role")]
    public int? SelectedRoleId { get; set; }

    public IEnumerable<SelectListItem> Roles { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // fetch the roles
        // could come from a database or something
        var roles = new[] 
        { 
            new { RoleID = 1, RoleName = "Admin" }, 
            new { RoleID = 2, RoleName = "Foo" },
            new { RoleID = 3, RoleName = "Bar" },
            new { RoleID = 4, RoleName = "Baz" }, 
        };

        // Now we build the model
        var model = new UserRoleViewModel
        {
            EmployeeName = "John", // could come from a database or something
            SelectedRoleId = 1, // could come from a database or something
            Roles = new SelectList(roles, "RoleID", "RoleName")
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(UserRoleViewModel model)
    {
        return Content(
            string.Format(
                "Selected role for {0} is {1}", model.EmployeeName, model.SelectedRoleId
            )
        );
    }
}

最后一个观点:

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

...

<% using (Html.BeginForm()) { %>
    <%= Html.EditorFor(x => x.EmployeeName) %>
    <%= Html.DropDownListFor(x => x.SelectedRoleId, Model.Roles, "-- Role --") %>
    <button type="submit">OK</button>
<% } %>