【问题标题】:Object reference error using Partial Views使用局部视图的对象引用错误
【发布时间】:2013-02-14 16:51:56
【问题描述】:

我收到普遍存在的“对象引用”错误,但不知道如何解决。我相信这与调用局部视图有关。我使用的是 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?谢谢。

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:

    您的部分需要一个模型

    @model MyViewModel
    

    你要么需要传递一个模型

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

    或者使用子 Action 并调用你的部分

    @Action("_MyPartialView");
    

    有对应的Action

        public ActionResult _MyPartialView()
        {
    
            MyViewModel model = new MyViewModel();
            return View(model)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2013-03-29
      相关资源
      最近更新 更多