将所选下拉选项的ID传递给Controller

时间:2012-03-21 07:49:12

标签: asp.net-mvc-3 nhibernate html.dropdownlistfor

我正在使用mvc3 nhibernate并创建一个搜索应用程序... 在这里,我创建一个包含所有Hobby名称的下拉列表,点击搜索按钮,所选选项的id应该转到post方法 我在我的控制器中写了以下代码

public ActionResult Details()
{

ViewBag.h=new SelectList(new Hobby_MasterService().GetHobbies(),"Hobby_Id");

return View();
}
[HttpPost]
public ActionResult Details(int Hobby_Id)
{
Hobby_Master hm = new Hobby_MasterService().GetHobby_Data(Hobby_Id);
return RedirectToAction("Show");
}

并且在视图中我只显示一个下拉列表

<b>Select Hobby:</b>
@using (Html.BeginForm("Details", "Hobbies", FormMethod.Get))
{
 <div class="Editor-field">
  @Html.DropDownListFor(Model => Model.Hobby_Id, (IEnumerable<SelectListItem>)ViewBag.h)

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

我的下拉列表是通过一个具有正常sql语句的函数填充的... 我可以生成列表.... 但我将如何获得所选择的爱好id ... 请帮忙

2 个答案:

答案 0 :(得分:0)

表格上可能有FormMethod.Post吗?

你的模特是一个类吗? 也许你可以接受在你的邮政行动中,然后你会发现它的身份。

答案 1 :(得分:0)

不用打扰模型绑定,只需在POST方法中添加一个FormCollection参数即可。该集合包含发布的所有表单值。

[HttpPost]
public ActionResult Details(FormCollection collection)
{
  Hobby_Master hm = new Hobby_MasterService().GetHobby_Data(Hobby_Id);
  if (collection["Hobby_Id"] != null)
  {
   // collection["Hobby_Id"] contains the value selected in the dropdown box
  }
  return RedirectToAction("Show");
}