Ali Almohsen Ali Almohsen - 7 months ago 30
C# Question

Render PartialView from Controller

HomeController > Index action does a select query. For each row in that select query, I need to render a Partial View in my Index view. Since this depends on the database, I'm doing this part of the code from the controller. I searched quite a bit, but I can't figure out how to render a PartialView from the controller.

  1. Do partial views require a controller action? I wasn't sure about this, but this is what I created:

    public PartialViewResult ucDropdown(Question question)
    ViewBag.Question = question;
    return PartialView();

  2. In my main view, how do I call this partial view? I have (unsuccessfully) tried:

    public ActionResult Index(string id = "")
    var q = ......
    var ctrls = new ControlsController();
    ViewBag.Questions = ctrls.ucDropdown(q);
    return View();

  3. How can I access the ViewBag of this partial view?


You do not necessarily need an action method to render a partial view. You can directly call the partial view in your main view and pass a Question object directly.

So in your main view, you can loop through the questions and call the partial view using Html.Partial helper method.

@foreach(var item in (List<Question>)ViewBag.Questions)

Assuming you have a partial view called ucDropdown.cshtml in either ~/Views/Shared directory or ~/Views/YourControllerFolderName and ViewBag.Question is of type List<Question> or IEnumerable<Question>

Make sure your partial view ucDropdown.cshtml is strongly typed to Question type

@model Question

Since you are passing the question object directly to view (a strongly typed approach), you do not need ViewBag. You can simply access Model.AnyPropertyName in your partial view.