2

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.

2 Answers 2

2

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

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

Comments

0

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?

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.