0

大家好,我必须从下拉列表中获取所选值到控制器中的 post 方法中。我该怎么做

这是我的控制器

       [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult AddNew()
    {          
        ViewBag.Roles = new SelectList(List(), "RoleID", "RoleName");           
        return View();
    }
    //
    //Geting All Roles In a GetRoles()/
    //
    public List<ResourceModel> List()
      {
          var roles = new List<ResourceModel>();
        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++)
        {                                
            var model = new ResourceModel();
            model.RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]);
            model.RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString();               
            roles.Add(model);
        }
          conn.Close();
          return roles ;
      }

    //
    //To perform the AddNew Logic..i.e it adds a new employee to DB/
    //
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AddNew(ResourceModel model)
    {
        // var modelList = new List<ProjectModel>();
        using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
        {
            conn.Open();
            SqlCommand insertcommande = new SqlCommand("InsertEmplyoee", conn);
            insertcommande.CommandType = CommandType.StoredProcedure;
            insertcommande.Parameters.Add("@EmployeeName", SqlDbType.VarChar).Value = model.EmployeeName;
            insertcommande.Parameters.Add("@EmployeeEmailId", SqlDbType.VarChar).Value = model.EmployeeEmailId;
            insertcommande.Parameters.Add("@EmployeePassword", SqlDbType.VarChar).Value = model.EmployeePassword;
            insertcommande.Parameters.Add("@GroupName", SqlDbType.VarChar).Value = model.RoleName;
            insertcommande.ExecuteNonQuery();
        }
        return View();
    } 

现在我想在我的 postmethod 中获取选定的值@GroupName 参数...任何人都可以帮助如何做到这一点

这是我的html

  <%:Html.DropDownList("Roles")%>
4

2 回答 2

0

您可以让您的 POST 操作采用视图模型,或者向其中添加另一个参数来保存所选值:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNew(ResourceModel model, string roles)

如果您打算重新显示相同的视图,请不要忘记以ViewBag.Roles与您在 GET 操作中相同的方式在您的 POST 操作中重新填充。

于 2012-07-19T06:31:39.410 回答
0

您可以Request.Form["Roles"]在控制器操作中使用.. 但也许更好的解决方案是为页面创建一个新的视图模型,您可以使用Html.DropDownListFor(m => m.RoleID, rolesSelectList)或其他任何东西.. 并且该值将在 udpate 方法中自动绑定到您的模型:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult AddNew(ResourceModel model) 
于 2012-07-19T06:34:15.063 回答