【问题标题】:ViewModel returned by View (PartialView) is emptyView(PartialView)返回的ViewModel为空
【发布时间】: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


【解决方案1】:

不确定 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

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多