should I be using an @html.renderpartial or @html.renderaction
Asked Answered
C

2

7

I'm trying to bring in my menu.

In my _Layout.cshtml page I have

<div class="wrapper">
                <!-- Navigation -->

                  @Html.RenderAction("Navigation", "Nav")

The Nav Controller looks like this

public ActionResult Navigation()
{
    var pages = pageRepository.Pages;
    return View(pages);
}

The Navigation View Looks like this

@model IEnumerable<Site.Domain.Entities.Page>
@{
    Layout = null;
    List<Site.Domain.Entities.Page> pages = new List<Site.Domain.Entities.Page>();

    foreach(var page in Model)
    {
        pages.Add(page);
    }
}

@foreach (var link in Model)
{
    if (link.ParentPage == "Home")
    { 
    <li>@link.PageTitle</li>
    <ul>
        @foreach (var subLink in pages)
        {
            if (subLink.ParentPage == link.PageTitle)
            { 
            <li>@subLink.PageTitle</li>
            }
        }
    </ul> 

    }
}

The view works fine when I go to .../nav/navigation

What I'm trying to do is bring this into my _Layout page so that I can use it as my menu.

I continue to get an error with @Html.RenderAction("Navigation", "Nav")

The error says "The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments"

Should I be using this as a partial? What is the best way to go about this? Thanks for any advice!

Convict answered 25/1, 2013 at 16:54 Comment(1)
Use the debugger to find what is happening.Retroaction
P
12

For what you're trying to do, @Html.RenderAction(..) is the correct call. RenderAction is ChildActionExtension and will need to add that attribute to the controller.

Your controller should look something like below. Note that you will want to return a PartialView as well.

[ChildActionOnly]
public ActionResult Navigation()
{
    var pages = pageRepository.Pages;
    return PartialView(pages);
}

The Render action does not return HTML, but rather adds the content to the response. With that, your view should look like:

@{@Html.RenderAction("Navigation", "Nav");}

Reference: http://msdn.microsoft.com/en-us/library/ee721274(v=vs.108).aspx

Proportional answered 25/1, 2013 at 17:3 Comment(2)
Please do not use secon @ in MVC5 . Correct Syntax: @{Html.RenderAction("Navigation", "Nav");}Boogie
@{Html.RenderAction("Navigation");} syntax to render the actionBattalion
T
3

Because Html.RenderAction is a void and does not return a value, you need to "escape" the call with braces

@{Html.RenderAction("Navigation", "Nav");}

In your controller, you should return a partial view instead.

public ActionResult Navigation()
{
    var pages = pageRepository.Pages;
    return PartialView(pages);
}
Twila answered 25/1, 2013 at 17:6 Comment(1)
Just use @Html.Action("Navigation","Nav") in MVC5Boogie

© 2022 - 2024 — McMap. All rights reserved.