如何将列绑定到DropDownList并在MVC3中获取值Selected?

时间:2012-07-18 07:11:55

标签: asp.net-mvc-3 c#-4.0 html-select

嗨,大家好我有两张看起来像这样的桌子

          usertable                                 RoleTable
   -----------------------                     ---------------------------
  UserID|UserName|Pwd|RoleID                        RoleID|RoleName
    1   |Anil    |123|1                               1   |Admin

现在我在一个表中显示usertable,他有一个AddNew Link,当管理员点击AddNew链接时,我会向他显示AddNew页面,他有一些标签和文本框给AddNew用户,

现在我要做的是在AddNew页面中我想在DropDown中显示所有RoleNames,以便管理员可以选择用户必须在哪个角色....我想要检索所选数据< / p>

这是我的模特课

         public class ResourceModel
{
    public static List<ResourceModel> GetList { get; set; }
    public Int16 EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public string EmployeeEmailId { get; set;}
    public string GroupName { get; set; }
    public string EmployeePassword { get; set; }

}

这是我的控制器

            [AcceptVerbs(HttpVerbs.Get)]
     public ActionResult AddNew()
    {

        ViewBag.Roles = new SelectList(GetRoles(),"RoleID","RoleName");           
        return View();
    }
    //
    //Geting All Roles In a GetRoles()/
    //
      public static GetRoles()
      {

        SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True");
        SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from  EmployeeGroup", conn);
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter(Cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            //roles.Add(new SelectListItem{.Value=i,.Text=i};                   
            var model = new ResourceModel();
            model.RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]);
            model.RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString();
            //roles.Value=Convert.ToString( model.RoleId);
            //roles.Text=model.RoleName;
        }
        conn.Close();
          return ds ;
      }

我必须在上面的代码中返回

这是我的AddNew Aspx页面

     <div>
    <% using (Html.BeginForm())
  { %>
  <%-- <form action="Create.aspx" method="post"></form>--%>
   <%:Html.ValidationSummary(true)%>
     <fieldset>
   <legend style="color:Orange; font-weight:bolder;">AddNew Project</legend>

    <div class="editor-label" style="color:Orange; font-weight:bolder;">
        <%: Html.LabelFor(model => model.EmployeeName)%>
    </div>
    <div class="editor-field">
       <%:Html.EditorFor(model => model.EmployeeName)%>
      <%: Html.ValidationMessageFor(model => model.EmployeeName)%>
    </div>

    <div class="editor-label" style="color:Orange; font-weight:bolder;">
       <%:Html.LabelFor(model => model.EmployeeEmailId)%>
    </div>
    <div class="editor-field">
       <%:Html.EditorFor(model => model.EmployeeEmailId)%>
       <%:Html.ValidationMessageFor(model => model.EmployeeEmailId)%>
    </div>
    <div class="editor-label" style="color:Orange; font-weight:bolder;">
    <%:Html.LabelFor(model => model.EmployeePassword)%>
    </div>
    <div class="editor-field">
    <%:Html.EditorFor(model => model.EmployeePassword)%>
    <%:Html.ValidationMessageFor(model => model.EmployeePassword)%>
    </div>
      <div class="editor-label" style="color:Orange; font-weight:bolder;">
    <%:Html.LabelFor(model => model.GroupName)%>
    </div>
    <div class="editor-field">
    <%:Html.EditorFor(model => model.GroupName)%>
    <%:Html.ValidationMessageFor(model => model.GroupName)%>
    <p>
        <input type="submit" value="Create" style="color:Orange; font-weight:bolder;"/>
    </p>
    </fieldset>
    <%} %>        
  </div>

任何人都可以在MVC3中帮助我这样做....我必须在DropDown中显示RoleNames我必须在控制器中检索我的[AcceptVerbs(HttpVerbs.Post)]中选择的值....任何想法,请

我有一个MY [AcceptVerbs(HttpVerbs.Post)]的存储过程,其中使用所选的下拉值,我将在Db中插入RoleName的RoleID

     Create Procedure InsertEmplyoee
       (
       @EmployeeName varchar(50),
       @EmployeeEmailId varchar(50),
      @EmployeePassword varchar (50),
       @GroupName varchar (50)
          )
       as
       begin
       insert into EmployeeDetails   (EmployeeName,EmployeeEmailId,EmployeePassword,GroupId) values 
    (@EmployeeName,@EmployeeEmailId,@EmployeePassword,(select GroupId from   EmployeeGroup where EmplopyeeRole=@GroupName ))

端 去

2 个答案:

答案 0 :(得分:1)

考虑如何将所选角色ID POST转回服务器。

而不是public static List<ResourceModel> GetList { get; set; }使用 public int RoleId {get;set;}。您无法为@Html.DropDownListFor创建List<T>,这是没有意义的,您只需发回一个值。

接下来,在模型中创建一个返回IEnumerable SelectListItem的方法。

public static IEnumerable<SelectListItem> GetRoles()
    {
        var roles = //However you plan to get this data from db
        return roles.Select(o => new SelectListItem
                                     {
                                         Value = o.RoleID,
                                         Text = o.RoleName
                                     });
    } 

最后在您看来:

@Html.DropDownListFor(x=> x.RoleId, ResourceModel.GetRoles())

答案 1 :(得分:0)

让你的行动像这样:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddNew()
{
        ViewBag.RoleId = new SelectList(GetRoles(), "RoleID", "RoleName");
        return View();
}

GetRoles应返回Role

列表

在您看来:

@Html.DropDownList("RoleId")

编辑:说明

Html.DropDownList方法将搜索ViewBag(实际为ViewData)以查找名称为SelectListItem的{​​{1}}列表,并使用该列表创建DropDown列表。您无需自己明确指定列表。

修改:更正RoleId

GetRoles方法应该是这样的:

GetRoles

我一直与public static List<Role> GetRoles() { SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"); SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from EmployeeGroup", conn); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(Cmd); DataSet ds = new DataSet(); da.Fill(ds); List<Role> allRoles = new List<Role>(); for(int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { Role role = new Role { RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]), RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString() }; allRoles.Add(role); } conn.Close(); return allRoles; } 合作。你为什么不和那个或其他ORM一起去?