0

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?

Evildommer5
  • 139
  • 3
  • 15

1 Answers1

2

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);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • the error i got "CS1928: 'System.Web.Mvc.HtmlHelper>' does not contain a definition for 'Partial' and the best extension method overload 'System.Web.Mvc.Html.PartialExtensions.Partial(System.Web.Mvc.HtmlHelper, string, object, System.Web.Mvc.ViewDataDictionary)' has some invalid arguments – Evildommer5 Mar 05 '13 at 15:46
  • @DarinDimitrov, Could we use `@Html.Action()` ? Or when we prefer which is the better? – AliRıza Adıyahşi Mar 05 '13 at 15:48
  • @Evildommer5, you should use `Html.Action()` instead of `Html.Partial()`. I have updated my answer. – Darin Dimitrov Mar 05 '13 at 15:59
  • There is no ViewData item of type 'IEnumerable' that has the key 'CategoryID'. Is my dropdown set properly? @Html.DropDownList("CategoryID", string.Empty) – Evildommer5 Mar 05 '13 at 16:00
  • 1
    Did you replace the `@Html.Partial` with `@Html.Action`? – Darin Dimitrov Mar 05 '13 at 16:02
  • This now returns the error Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. – Evildommer5 Mar 05 '13 at 16:04
  • In your _Quickblah controller action replace `return View(blah);` with `return PartialView(blah);` – Darin Dimitrov Mar 05 '13 at 16:15
  • 1
    Do you have a view called `_Quickblah.cshtml` for the same controller? Also what's in the exception stacktrace? – Darin Dimitrov Mar 05 '13 at 16:20