0

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?

1 Answer 1

2

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)
{
  @Html.Partial("ucDropdown",item)
}

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
<p>@Model.QuestionId</p>

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.