MVC方法让我很难理解我如何实际检索数据。
查看
<p>
@using (Html.BeginForm("About"))
{
<span style="margin-top: 1em; float: right;">
Filter Zone Area @Html.DropDownList("ZoneArea", new SelectListItem[]
{
new SelectListItem() { Text = "All", Value = "0" },
new SelectListItem() { Text = "North", Value = "1" },
new SelectListItem() { Text = "South", Value = "2"},
new SelectListItem() { Text = "East", Value = "3" },
new SelectListItem() { Text = "West", Value = "4" },
new SelectListItem() { Text = "Central", Value = "5" },},
new { @onchange = "this.form.submit()" })
</span>
}
</p>
控制器
public ActionResult About(School model, FormCollection form)
{
string strDDLValue = form["ZoneArea"];
var schooList = schGateway.SelectAll();
schooList = schooList.Where(s => s.Zone_Id == 1);
if (schooList != null)
{
foreach (var school in schooList)
{
string[] schLoc = new string[] { school.School_Name, school.Dus_Lat.ToString(), school.Dus_Long.ToString() };
model.SchooList.Add(schLoc);
}
}
return View(model);
}
当我在下面调试此代码时,它返回空值
string strDDLValue = form["ZoneArea"];
答案 0 :(得分:1)
代码中没有问题。我可以通过在视图和控制器中使用完全相同的代码来获取值。区别在于@using(Html.BeginForm(“About”,“Default”)),其中Default是控制器名称。如果我们使用Request.Form [“ZoneArea”],那么我们可以摆脱FormCollection参数。
Stephen Muecke在评论中给出的解决方案是正确的方法,但在这里我只是说从代码中查看控制器中的值没有错误。
public ActionResult Index()
{
ViewBag.SelectList = GetDict();
return View();
}
public ActionResult About()
{
string strDDLValue = Request.Form["ZoneArea"];
ViewBag.SelectedValue = strDDLValue;
ViewBag.SelectList = GetDict();
return View("Index");
}
public Dictionary<string,int> GetDict()
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("All", 0);
dict.Add("North", 1);
dict.Add("South", 2);
dict.Add("East", 3);
dict.Add("West", 4);
dict.Add("Central", 4);
return dict;
}
查看:
@using (Html.BeginForm("About","Default"))
{
<span style="margin-top: 1em; float: right;">
Filter Zone Area @Html.DropDownList("ZoneArea", new SelectList(ViewBag.SelectList,"value","key",ViewBag.SelectedValue),
new { @onchange = "this.form.submit()" })
</span>
}