1

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

我有一个表格可以将角色分配给每个员工。所以我创建了一个表单,我可以输入员工的姓名并选择他们所在的角色。角色从表 Role 中获取。我使用 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<> 。

谢谢。

4

1 回答 1

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>
<% } %>
于 2012-07-06T12:16:36.903 回答