私のビューモデルがビューによって空として返される理由を理解するのを手伝ってください。Google で解決策を見つけようとしましたが、ほとんどのアドバイスは非表示を追加することです。しかし、私にとっては 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>