使用部分视图的对象引用错误

M E*_*rty 0 asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我正在获得无处不在的"对象引用"错误,并且不知道如何解决它.我认为这与调用局部视图有关.我正在使用jquery向导,因此部分视图是向导中显示的"步骤".

在我的主.cshtml视图中,我这样做(我忽略了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"); }
    ...
}
Run Code Online (Sandbox Code Playgroud)

上面的工作(至少它在我得到我的错误之前通过).

这是我的部分视图(再次,省略HTML):

@using MyNamespace.Models
@using MyNamespace.ViewModels
@model MyViewModel
....
// I get the object reference error here
@if (Model.MyModel.MyRadioButton == RadioButtonChoice.One)
{
    // display something
}
....
Run Code Online (Sandbox Code Playgroud)

我很困惑,因为除了@ifvs. if,它基本上是相同的代码.我不知道我做错了什么,或者如何解决.

对于上下文,这里是MyViewModel:

public class MyViewModel
{
    public MyModel MyModel { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

MyDropDownMyRadioButton使用enums正是如此:

public enum DropDownChoice { One, Two, Three }
public enum RadioButtonChoice { One, Two, Three }

public DropDownChoice? MyDropDown { get; set; }
public RadioButtonChoice? MyRadioButton { get; set; }
Run Code Online (Sandbox Code Playgroud)

我的控制器只对主窗体执行操作,而对局部视图没有操作:

public ActionResult Form()
{
    return View("Form");
}

[HttpPost]
public ActionResult Form(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        return View("Submitted", model);
    }
    return View("Form", model);
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我是否必须ActionResult为该局部视图创建一个即使没有直接调用它(除了向导中的部分视图)?谢谢.

Dav*_*ich 5

你的部分需要一个模型

@model MyViewModel
Run Code Online (Sandbox Code Playgroud)

您需要传递模型

@{ Html.RenderPartial("_MyPartialView", MyViewModel);
Run Code Online (Sandbox Code Playgroud)

或者使用一个孩子动作并用你的部分召唤

@Action("_MyPartialView");
Run Code Online (Sandbox Code Playgroud)

与相应的行动

    public ActionResult _MyPartialView()
    {

        MyViewModel model = new MyViewModel();
        return View(model)
    }
Run Code Online (Sandbox Code Playgroud)