1

请帮助我理解为什么我的视图模型被视图返回为空。我试图在谷歌中找到解决方案,但绝大多数建议是添加隐藏。但对我来说,添加 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>
4

1 回答 1

0

不确定4年后您是否仍在寻找答案,但我遇到了同样的事情并找到了这个解决方案:

改变你的

@Html.Partial("_FilterPartial", Model.Filter)

@Html.Partial("_FilterPartial", Model.Filter,
       new ViewDataDictionary(Html.ViewData)
       {
            TemplateInfo = new TemplateInfo { HtmlFieldPrefix = Html.NameFor(m => m.Filter).ToString() }
       })

我在这里找到了答案

于 2017-04-06T19:27:13.910 回答