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
}
....

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

对于上下文,这里是MyViewModel

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

MyDropDownandMyRadioButton正在这样使用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即使没有直接调用它(除了作为向导中的局部视图),我是否必须为该局部视图创建一个?谢谢你。

4

1 回答 1

5

您的部分需要一个模型

@model MyViewModel

你要么需要传递一个模型

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

或使用子操作并使用

@Action("_MyPartialView");

有相应的动作

    public ActionResult _MyPartialView()
    {

        MyViewModel model = new MyViewModel();
        return View(model)
    }
于 2013-02-14T17:01:52.453 回答