简体   繁体   中英

Viewbag not working in Explicit Partial View

I have a list view And i want to add a create partial to the page.

@model IEnumerable <blah.Domain.Entities.blah>

@Html.Partial("_Quickblah", new blah.Domain.Entities.blah());

  public ViewResult _Quickblah()
        {
            ViewBag.CategoryID = new SelectList(Repository.Categorys, "CategoryID", "Title");

            Blah blah = new Blah () { CreatedDate = DateTime.Now };

            return View(blah);
        }

and i get the error

There is no ViewData item of type 'IEnumerable' that has the key 'CategoryID'.

how can i fix this?

When you call Html.Partial your _Quickblah controller action is not called and of course the ViewBag.CategoryID is not assigned (because I assume that in your main controller action that rendered this view you didn't set it). You should use Html.Action instead:

@Html.Action("_Quickblah")

Also in your _Quickblah action make sure that you are returning a partial view:

public ActionResult _Quickblah()
{
    ViewBag.CategoryID = new SelectList(Repository.Categorys, "CategoryID", "Title");
    Blah blah = new Blah () { CreatedDate = DateTime.Now };
    return PartialView(blah);
}

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