简体   繁体   中英

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

Here are my 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.

When you use @Html.Action you have to handle the flow, what view will you render, what model it will be and others...

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.

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.

Partial view code:

In the partial view you have your code as it currently is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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