View(PartialView)返回的ViewModel为空

时间:2013-04-09 12:49:37

标签: asp.net-mvc-4 asp.net-mvc-partialview asp.net-mvc-viewmodel

请帮助我理解为什么我的视图模型被视图返回为空。我试图在谷歌找到解决方案,但绝大多数建议是添加隐藏。但是对我来说添加Html.HiddenFor没有工作

这是我的代码

的ViewModels

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" />
}

PartialView

@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>

1 个答案:

答案 0 :(得分: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() }
       })

我找到了答案here