2013-02-14 67 views
0

我得到无处不在的“对象引用”错误,不知道如何解决它。我相信这与调用局部视图有关。我正在使用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"); } 
    ... 
} 

上述工作(至少它通过之前,我得到我的错误)。

这里是我的局部视图(同样,离开了HTML):

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

我很困惑,因为与@ifif外,它本质上是相同的代码。我不知道我做错了什么,或者如何解决。

为背景,这里是MyViewModel

public class MyViewModel 
{ 
    public MyModel MyModel { get; set; } 
} 

而且MyDropDownMyRadioButton使用enums正是如此:

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

public DropDownChoice? MyDropDown { get; set; } 
public RadioButtonChoice? MyRadioButton { get; set; } 

我控制器只有为主要形式和动作的任何动作局部视图:

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

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

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

回答

5

你的部分需要一个模型

@model MyViewModel 

你要么需要通过一个模型

@{ Html.RenderPartial("_MyPartialView", MyViewModel); 

或者用一个孩子的行动,并调用相应的部分与

@Action("_MyPartialView"); 

动作

public ActionResult _MyPartialView() 
    { 

     MyViewModel model = new MyViewModel(); 
     return View(model) 
    } 
相关问题