如何在控制器中获取 Html.DropDownList 的值?

How to get value of Html.DropDownList in the controller?

我在controller中分配了以下viewbag

public ActionResult new_vehicle()
    {
        ViewBag.customers = new SelectList(db.customers, "cust_id", "cust_name");
        return View(db.vehicles.ToList());
    }

查看代码为

 @Html.DropDownList("customers", "Select Customer");

添加函数的代码是

public ActionResult veh_AddEdit()
    {
        int id = Convert.ToInt32(Request["vehiddenID"]);
        if (id == 0)
        {

            vehicle veh = new vehicle();
            Session["veh_id"] = "";

            veh.cust_id_fk = Convert.ToInt32(Request.Form["customers"]);
            veh.veh_make = Request["vemake"];
            veh.veh_name = Request["vename"];
            veh.veh_model = Request["vemodel"];
            db.vehicles.Add(veh);
            db.SaveChanges();
            int latestEmpId = veh.veh_id;
        }

        return RedirectToAction("new_vehicle");
    }

问题是它没有获得选定的值,即控制器中的外键。

在您的控制器中,您可以传入 viewbag IEnumerable<SelectListItem>

public ActionResult new_vehicle()
{
    ViewBag.customers = db.customers.Select(i=>new SelectListItem() { Text = i.cust_name, Value=i.cust_id });
    return View(db.vehicles.ToList());
}

然后在您的视图中,您可以像那样呈现下拉菜单

@Html.DropDownList("customers", (IEnumerable<SelectListItem>)ViewBag.customers, "Select Customer")

然后在您的控制器中使用您的方法 veh_AddEdit 您可以像 Request["customers"]

一样访问它

我希望你从维克多的回答中得到了解决方案,在这里我想提供额外的信息,希望它能帮助你更好地理解

在一般的 Html 形式中,将使用键值对将值发送到控制器。因此下拉列表名称将是键,值将是用户选择的。

要检查 html 为下拉列表呈现后,只需转到浏览器中的查看页面源代码并获取控件的名称以在操作方法中使用它。

例如:

public ActionResult veh_AddEdit(string customers)
    {
        int id = Convert.ToInt32(Request["vehiddenID"]);
        if (id == 0)
        {

            vehicle veh = new vehicle();
            Session["veh_id"] = "";

            veh.cust_id_fk = Convert.ToInt32(customers);
            veh.veh_make = Request["vemake"];
            veh.veh_name = Request["vename"];
            veh.veh_model = Request["vemodel"];
            db.vehicles.Add(veh);
            db.SaveChanges();
            int latestEmpId = veh.veh_id;
        }

        return RedirectToAction("new_vehicle");
    }