Passing Parameters from View to Action in MVC

时间:2015-07-02 21:03:40

标签: mysql linq asp.net-mvc-4

I am currently trying to take a value from a drop down list, store it into a variable, and pass it into a controller's action result. When I run my code, the Index is supposed to store the value of the selected item in the dropdown box in the variable SelectedDistrict, then then go to the Query action. Query will take a variable of DistrictViewModel as a parameter and then use var school = getQuery(variable.SelectedDistrict) to go into the function I have. In the function however, it's saying that the variable sd is null whenever i debug. Maybe the value from the drop down box is not storing properly? In the end, I want to display in a table all of the schools in my school table that come from the selected district in the drop down. The table is not being populated because of the null value. Here is my code for more clarity.

  • District View Model:

District View Model

  • School View Model:

enter image description here

  • Controller w/ getQuery function:

enter image description here

  • Index View:

enter image description here

  • Query View:

enter image description here

  • The table when I run my code:

1 个答案:

答案 0 :(得分:1)

问题是你的Query控制器方法期望一些数据以对象的形式传递,但你没有传递任何数据。如果它是GET请求(并且看起来是因为您只是在点击时设置了location.href),则值必须在查询字符串中。或者,您可以将表单POST设置为该控制器操作。

您需要<form>个标签。您可以GET或POST到您的控制器方法,这无关紧要(模型绑定无论哪种方式)。这取决于您是否希望人们能够直接深入链接到搜索结果。

<form action="@Url.Action("Query", "District") method="get">
  @Html.DropDownListFor(m => m.SelectedDistrict, Model.Districts)
  <button type="submit" value="Submit"/>
</form>

应该这样做,或者至少让你走上正确的道路。