简体   繁体   English

MVC RenderPartial 模型始终为空

[英]MVC RenderPartial model is always null

I tried making a partial view, actually it works but when I tried to put my code in html, I always get a Nullable error.我尝试制作局部视图,实际上它有效,但是当我尝试将代码放入 html 时,我总是收到Nullable错误。 This work :这项工作:

public PartialViewResult Notification()
{
    ViewBag.Notification = db.Notification.ToList();
    return PartialView("Notification");
}

@Html.Action("Notification", "Project");

but when I tried to make it like this:但是当我尝试这样做时:

public PartialViewResult Notification()
{
    ViewBag.Notification = db.Notification.ToList();
    return PartialView("Notification");
}

@Html.RenderPartial("Notification", "Project");

or或者

@Html.RenderPartial("Notification", "Project");

Such codes give me a Nullable error这样的代码给了我一个Nullable错误

Here are my PartialView这是我的 PartialView

@{
    foreach (var item in ViewBag.Notification)
    {
         @item.Name
    }
}

如果你想使用 @html.RenderPartail 那么这个 ViewBag 东西将不起作用,因为这不会触发动作,但你仍然想使用它那么你应该在 @Html.RendrePartial 本身中传递一个模型对象。

If you want to use @Html.RenderPartial you no longer need your Notification Action.如果你想使用@Html.RenderPartial你不再需要你的通知操作。

When you use @Html.Action you have to handle the flow, what view will you render, what model it will be and others...当您使用@Html.Action您必须处理流程,您将呈现什么视图,它将是什么模型等等......

When you call @Html.RenderPartial you are asking for microsoft code to handle the flow, and it will do, it will provide the view you want as you did by using @Html.Action , you just have to fill parameters.当您调用@Html.RenderPartial您要求微软代码来处理流程,它会这样做,它会像使用@Html.Action一样提供您想要的视图,您只需要填写参数。

I guess that this partial view you want to render is a not typed one, ok then.我猜你想渲染的这个局部视图是一个没有输入的视图,那么好吧。

You should do this way:你应该这样做:

View action:查看操作:

public ActionResult PreviousAction()
{    
    ViewBag.Notification = db.Notification.ToList();    
    return View();
}

View code:查看代码:

@{ Html.RenderPartial("Notification"); }

The parameter Notification you are passing, is not an Action name anymore, now it's the name of partial view that you are asking for Microsoft code to render.您传递的参数Notification不再是 Action 名称,现在它是您要求 Microsoft 代码呈现的部分视图的名称。

Partial view code:部分查看代码:

In the partial view you have your code as it currently is:在局部视图中,您拥有当前的代码:

@{
    foreach (var item in ViewBag.Notification)
    {
         @item
    }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM