【发布时间】:2015-03-28 17:29:19
【问题描述】:
将 ViewModel 传递给 @Html.Partial
有两个 ViewModel
public class RegisterVM
{
... some properties
public AddressVM AddressInformation { get; set; } //viewmodel
}
public class AddressVM {
public string Street1 { get; set; }
public string Street2 { get; set; }
public string PostalCode { get; set; }
}
使用 VM 加载主视图时:
@model ViewModels.RegisterVM
所有字段加载。但是当我添加部分视图并传递视图模型时
@Html.Partial("_AddressDetails", Model.AddressInformation)
失败了 错误:异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。为什么会失败?
部分视图 _AddressDetails 需要一个
@model ViewModels.AddressVM
更新
基于 Prashant 的更改,
提交信息时地址信息为NULL。 在控制器中:
[HttpPost]
public ActionResult Register(RegisterVM vm){
...
//when viewing vm.AddressInformation.Street1 is null. and there is a value
//Is there a different way of retrieving the values from partial view?
}
感谢阅读。
【问题讨论】:
-
你确定实例化了Model和Model.AddressInformation吗?
-
@VsevolodGoloviznin 你的意思是实例化模型?在控制器中,我只有 public ActionResult Register(){ return View();如果我评论 Html.Partial 行,所有字段/文本框都会毫无例外地加载
-
您将
null值作为模型传递,这就是您获得 NullReference 的原因
标签: asp.net-mvc viewmodel partial-views