如何使用BeginForm从View中将DropDownList的SelectedValue发送到Controller?

时间:2014-11-01 19:13:11

标签: c# asp.net-mvc entity-framework

如何使用BeginForm从View中将DropDownList的SelectedValue发送到Controller?

这是我的代码:

@using (Html.BeginForm(new {  newvalue=ddl.SelectedValue}))
{

@Html.DropDownList("categories", 
     (List<SelectListItem>)ViewData["categories"], 
      new { onchange = "this.form.submit()", id = "ddl" })

1 个答案:

答案 0 :(得分:1)

请勿使用ViewDataViewBag代替您的型号。它很草率,容易出错,只是一种无组织的方式来提供你的观看数据。

放置在表单本身上时,

{ newvalue=ddl.SelectedValue}对您无能为力。您需要了解所写的所有内容在发送到客户端之前都会在服务器上进行评估。因此,如果newvalue解析为1,它将继续保持1永久,除非你有javascript在客户端更改它(你没有做,你不应该这样做)。

首先你需要一个模型:

public class CategoryModel()
{
    public IEnumberable<SelectListItem> CategoriesList {get;set;}
    public int SelectedCategoryId {get;set;}

}

控制器

public class CategoryController()
{
    public ActionResult Index()
    {
        var model = new CategoryModel();
        model.CategoriesList = new List<SelectListItem>{...};
        return View(model);
    }

    public ActionResult SaveCategory(CategoryModel model)
    {
        model.SelectedCategoryId
        ...
    }
}

查看

@model CategoryModel
@using(Html.BeginForm("SaveCategory","Category"))
{
   @Html.DropDownListFor(x=> x.SelectedCategoryId, Model.CategoriesList)
   <button type="submit">Submit</button>
}

这里发生的事情是正在从IEnumerable中填充SelectList,它的表单名称是SelectedCategoryId,这就是提交给服务器的内容。

我不确定你对http和html的知识在哪里结束,但你不应该使用任何框架,直到你理解http和html如何工作,然后这些帮助者如begin form and Html.DropDownList实际为你做了什么。在尝试使用螺丝刀之前,请先了解螺丝的工作原理。

相关问题