【发布时间】:2013-04-09 12:49:37
【问题描述】:
请帮助我理解为什么我的视图模型被视图返回为空。我试图在谷歌中找到解决方案,但绝大多数建议是添加隐藏。但对我来说,添加 Html.HiddenFor 不起作用
这是我的代码
视图模型
public class MyViewModel
{
public FilterViewModel Filter {get; set;}
public MyViewModel()
{
Filter = new FilterViewModel();
}
}
public class FilterViewModel
{
public IEnumerable<SelectListItem> TimeUnits { get; set; }
public string SelectedTimeUnit { get; set; }
}
控制器
public class HomeController : Controller
{
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Filter.TimeUnits = new SelectList( new string[] {"week", "month", "year"});
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
*here I have empty model*
return View();
}
}
查看
@model Mvc4WebApplication.Models.MyViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.Filter.SelectedTimeUnit)
@Html.Partial("_FilterPartial", Model.Filter)
<input type="submit" class="ok" value="OK" />
}
部分视图
@model Mvc4WebApplication.Models.FilterViewModel
<div class="select">
<div class="background">
@Html.DropDownListFor(m => m.SelectedTimeUnit, Model.TimeUnits as SelectList, "Select time unit", new { onchange = "FetchPeriods();" })
</div>
</div>
提前感谢。
UPD 生成的 HTML 是这样的
<form action="/" method="post">
<input id="Filter_SelectedTimeUnit" name="Filter.SelectedTimeUnit" type="hidden" value="">
<div class="select">
<div class="background">
<select id="SelectedTimeUnit" name="SelectedTimeUnit" onchange="FetchPeriods();">
<option value="">Select time unit</option>
<option>week</option>
<option>month</option>
<option>year</option>
</select>
</div>
</div>
<input type="submit" class="ok" value="OK">
</form>
【问题讨论】:
-
生成的 HTMl 是什么样的?另外,你为什么在
EditorTemplate上使用部分_FilterPartial? -
我在上面的问题中添加了生成的 html。我在这里放了简化的例子。我在系统的几个地方使用了这个局部视图
-
为什么
SelectedTimeUnit被引用了两次;一次作为隐藏输入,第二次在局部视图中?我也从来没有看到TimeUnits显示。
标签: asp.net-mvc-4 asp.net-mvc-partialview asp.net-mvc-viewmodel