MVC 3

2012-04-17 50 views
1

的DropDownList的通行证的SelectedValue在Html.BeginForm()在ASP.NEt这是我查看代码:MVC 3

@using(Html.BeginForm(new { SelectedId = /*SelectedValue of DropDown*/ })) { 

<fieldset> 

    <dl> 
     <dt> 
      @Html.Label(Model.Category) 
     </dt> 
     <dd> 
     @Html.DropDownListFor(model => Model.Category, CategoryList) 
     </dd> 
    </dl> 

</fieldset> 
<input type="submit" value="Search" /> 


} 

如图所示的代码,我需要通过在BeginForm() HTML辅助的dropdown选择价值的行动。你有什么建议?

+1

你会如何知道在渲染时间选择的值? – Tuan 2012-04-17 08:11:20

+0

@Tutan这是我的问题,如果有任何答案 – Saeid 2012-04-17 08:16:40

回答

13

由于下拉列表由<select>元素表示,所以在提交表单时将传递所选值。你只需要调整您的视图模型,以便它有一个名为SelectedId例如要在其中绑定下拉属性:

@using(Html.BeginForm()) 
{ 
    <fieldset> 
     <dl> 
      <dt> 
       @Html.LabelFor(x => x.SelectedId) 
      </dt> 
      <dd> 
       @Html.DropDownListFor(x => x.SelectedId, Model.CategoryList) 
      </dd> 
     </dl> 
    </fieldset> 

    <input type="submit" value="Search" /> 
} 

这假定以下视图模型:

public class MyViewModel 
{ 
    [DisplayName("Select a category")] 
    public int SelectedId { get; set; } 

    public IEnumerable<SelectListItem> CategoryList { get; set; } 
} 

,这将是由你的控制器处理:

public ActionResult Index() 
{ 
    var model = new MyViewModel(); 
    // TODO: this list probably comes from a repository or something 
    model.CategoryList = new[] 
    { 
     new SelectListItem { Value = "1", Text = "category 1" }, 
     new SelectListItem { Value = "2", Text = "category 2" }, 
     new SelectListItem { Value = "3", Text = "category 3" }, 
    }; 
    return View(model); 
} 

[HttpPost] 
public ActionResult Index(MyViewModel model) 
{ 
    // here you will get the selected category id in model.SelectedId 
    return Content("Thanks for selecting category id: " + model.SelectedId); 
}