【问题标题】:How to bind a column to DropDownList and get the value Selected in MVC3?如何将列绑定到 DropDownList 并获取 MVC3 中 Selected 的值?
【发布时间】:2012-07-18 07:11:54
【问题描述】:

大家好,我有两张这样的桌子

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

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

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

这是我的模型类

         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 中帮助我这样做......我必须在下拉菜单中显示 RoleNames 我必须检索在控制器中的 [AcceptVerbs(HttpVerbs.Post)] 中选择的值......请有任何想法

我有一个我的 [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 ))

结束 去

【问题讨论】:

  • 各位大神可以帮帮我..........

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


【解决方案1】:

想一想你将如何将POST选定的角色ID返回到服务器。

而不是public static List&lt;ResourceModel&gt; GetList { get; set; } 使用 public int RoleId {get;set;}。您不能为List&lt;T&gt; 创建@Html.DropDownListFor,这没有任何意义,您只是返回一个值。

接下来在您的模型中创建一个方法,返回 IEnumerableSelectListItem

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=&gt; x.RoleId, ResourceModel.GetRoles())

【讨论】:

    【解决方案2】:

    让你的 Get Action 像这样:

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

    GetRoles 应该返回Role 的列表

    在你看来:

    @Html.DropDownList("RoleId")
    

    编辑:解释

    Html.DropDownList 方法将搜索ViewBag(实际上是ViewData)以查找名称为RoleIdSelectListItem 列表,并以此创建下拉列表。您无需自己明确指定列表。

    编辑:更正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;
    }
    

    我一直与EntityFramework 合作。为什么不使用那个 ORM 或其他一些 ORM?

    【讨论】:

    • @Mohayemin..我是否必须在我的 GetRoles() 方法中声明 RoleId ,RoleName
    • @anilkumar:只需在GetRoles() 方法中从数据库中返回所有Role 的列表。你的Role 类有RoleIdRoleName,不是吗?
    • @Mohayemin..是的,我的班级里确实有他们,但在下拉列表中我是空的
    • 如果你正确地从GetRoles()返回所有Role,你就不应该得到空的下拉列表。将调试指针放在return View() 行并检查ViewBag.RoleId 中的内容。让我知道结果。
    • @Mohayemin...你能检查我的 getroles() 方法吗..我在我的问题中发布了..我根据你的建议更改了我的代码...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多