使用局部视图对象引用错误 [英] Object reference error using Partial Views
问题描述
我越来越无处不在的对象引用的错误,不知道如何解决它。我相信这与调用的局部视图做。我使用jQuery的精灵,所以部分观点是在得到所显示的向导台阶。
I am getting the ubiquitous "object reference" error and don't know how to resolve it. I believe it has to do with calling a partial view. I am using a jquery wizard, so the partial views are the "steps" in the wizard that get displayed.
在我的主 .cshtml
查看我这样做(我要离开了HTML):
In my main .cshtml
view I do this (I'm leaving out the HTML):
@using MyNamespace.Models
@using MyNamespace.ViewModels
@model MyViewModel
...
...
using (Html.BeginForm())
{
...
// this works inside MAIN view (at least it goes through
// before I get my error)
if (Model.MyModel.MyDropDown == DropDownChoice.One)
{
//display something
}
...
// here i call a partial view, and in the partial view (see
// below) I get the error
@{ Html.RenderPartial("_MyPartialView"); }
...
}
以上工程(至少它通过之前,我给我的错误)。
The above works (at least it goes through before I get to my error).
下面是我的局部视图(同样,离开了HTML):
Here is my partial view (again, leaving out HTML):
@using MyNamespace.Models
@using MyNamespace.ViewModels
@model MyViewModel
....
// I get the object reference error here
@if (Model.MyModel.MyRadioButton == RadioButtonChoice.One)
{
// display something
}
....
我很困惑,因为在 @if
与如果
,它本质上是相同$ C除外$ C。我不知道我做错了,或如何解决。
I am confused because with the exception of the @if
vs. if
, it's essentially the same code. I do not know what I've done wrong, or how to fix.
有关的上下文,这里是 MyViewModel
:
For context, here is MyViewModel
:
public class MyViewModel
{
public MyModel MyModel { get; set; }
}
以及 MyDropDown
和 MyRadioButton
使用枚举
正是如此:
public enum DropDownChoice { One, Two, Three }
public enum RadioButtonChoice { One, Two, Three }
public DropDownChoice? MyDropDown { get; set; }
public RadioButtonChoice? MyRadioButton { get; set; }
我的控制器只有为主要形式的行动和局部视图没有动作:
My controller only has an action for the main form and no actions for the partial view:
public ActionResult Form()
{
return View("Form");
}
[HttpPost]
public ActionResult Form(MyViewModel model)
{
if (ModelState.IsValid)
{
return View("Submitted", model);
}
return View("Form", model);
}
有什么想法?难道我必须创建一个的ActionResult
因为即使有它没有直接调用(不是在向导的局部视图等)的局部视图?谢谢你。
Any thoughts? Is it that I have to create an ActionResult
for that partial view even though there is no direct call to it (other than as a partial view in the wizard)? Thank you.
推荐答案
您需要的部分模型
@model MyViewModel
您要么需要通过一个模型
You either need to pass a model
@{ Html.RenderPartial("_MyPartialView", MyViewModel);
或者使用一个孩子的行动,并致电部分以
Or use a child Action and call your partial with the
@Action("_MyPartialView");
相应行动
public ActionResult _MyPartialView()
{
MyViewModel model = new MyViewModel();
return View(model)
}
这篇关于使用局部视图对象引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!