如何使用ASP.NET Core将数据传递到部分视图?

时间:2019-04-03 20:43:33

标签: c# asp.net-core razor asp.net-core-mvc

免责声明:我是ASP.NET Core的新手,但已经阅读并尝试了很多。

我正在尝试实现我的第一个局部视图并将数据传递给它。从我所阅读的内容来看,这应该行得通,所以我对往南走的方向感到困惑。

我的局部视图:

    @page
    @model int
    @*

   *@
   <h2>@Model</h2>

我对部分视图的调用:

@Html.Partial("_ProductCreate", 0);
_ProductCreate的

C#代码是默认代码:

public class _ProductCreateModel : PageModel
{
    public void OnGet()
    {

    }
}

@Model始终为null。具体来说,我收到以下错误:

  

NullReferenceException:对象引用未设置为对象的实例。 aspnetcoreapp.Pages.Customers.Pages_Customers__ProductCreate.get_Model()

1 个答案:

答案 0 :(得分:0)

在与视图关联的控制器中,您需要将模型返回到视图。这在此处的线程中显示:Return List To View

以下是将模型传递到其中Example是我的模型类型的视图的简化方法。

    public ActionResult HomeController(Example model)
    { 
        return View(model);
    }   

如果您当时在Home视图中,则可以将相同的模型或模型的属性传递给局部视图,如下所示:

@* Declaring your model *@
@model Example.Web.Models.Example

@* Passing that same model through to the partial view *@
@Html.Partial("_ProductCreate", Model);