Bobby Ortiz
Bobby Ortiz

Reputation: 3147

Generate Partial View for Navigation in an MVC Controller

I am new to MCV3 and Razor. So far, I Looooooooove it.

I currently have a layout page with the navigation in a partial view. Here is a sample of what my partial view might look like now:

<ul id="nav-primary">
  <li>@Html.ActionLink("Facts", "Index", "LearnTheFacts")
    <ul>
      <li>@Html.ActionLink("What are the factors?", "Factors", "LearnTheFacts")</li>
      <li>@Html.ActionLink("How can this site help?", "KnowYourRisk", "LearnTheFacts")</li>
    </ul>
  </li>
  <li>@Html.ActionLink("Event Calendar", "Index", "EventCalendar")</li>
  <li>@Html.ActionLink("Another Topic", "Index", "Hello")
    <ul>
      <li>@Html.ActionLink("Call w/ Values", "Test", "Hello", new { runTest = true }, null)</li>
    </ul>
  </li>
</ul>

I would like to do something more complex that would involve generating the navigation from data in a database. Can I generate the above code completely in the controller and NOT use a partial view at all?

Ideally, I would like a single controller call. All content for the view would also be stored in the database. I believe the generated output for the navigation would be something like this:

<li>@Html.ActionLink("Menu Title 1", "Factors", "LearnMoreAbout", new { ID = 0 }, null)</li>
<li>@Html.ActionLink("Menu Title 2", "Factors", "LearnMoreAbout", new { ID = 1 }, null)</li>
<li>@Html.ActionLink("Menu Title 3", "Factors", "LearnMoreAbout", new { ID = 2 }, null)</li>
<li>@Html.ActionLink("Menu Title 4", "Factors", "LearnMoreAbout", new { ID = 3 }, null)</li>
<li>@Html.ActionLink("Menu Title 5", "Factors", "LearnMoreAbout", new { ID = 4 }, null)</li>
<li>@Html.ActionLink("Event Calendar", "Index", "EventCalendar")</li>

This is what I see myself writting, if I do it by hand. I would like to generate it.

Any ideas? Should I do something different? Thanks.

Upvotes: 2

Views: 5108

Answers (2)

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

i would do it using RenderAction where action method will fetch the data from db and pass it as model to the view which will generate the html

public ActionResult Navigation()
{
   var model = //fetch from db;
   return View(model);
}

and in view u can do something like

@foreach(var item in Model)
{
   <li>@Html.ActionLink("Menu Title 1", "Factors", "LearnMoreAbout", new { ID = item.ID }
}

RenderAction will generate a new call to the controller whether you use a view or just return content from it

Upvotes: 2

Adam Tuliper
Adam Tuliper

Reputation: 30152

You can... You can call Html.RenderAction and in your controller return Content("your HTML here") Why generate all from a DB though? Code may be a bit ugly that way?

Upvotes: 0

Related Questions