NomenNescio
NomenNescio

Reputation: 3030

MVC3 razor return current view

I've got a actionlink in my master page _Layout That when pressed, changes the layout of my menu. But I don't want the current Content of my page to change.

How can I accomplish this with MVC3 razor without using javascript?

I'm guessing it will be something along the lines of:

Especially the "return previous view" part perplexes me, could someone explain how to accomplish this?

Upvotes: 0

Views: 325

Answers (2)

Heather
Heather

Reputation: 2652

In your controller override OnActionExecuting:

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.QueryString["MenuLayoutName"] != null && IsValidMenuLayoutName(filterContext.RequestContext.HttpContext.Request.QueryString["MenuLayoutName"] != null))
            ViewBag.MenuLayoutName = filterContext.RequestContext.HttpContext.Request.QueryString["MenuLayoutName"];
    }

In your _Layout.cshtml when you render the menu, look at the ViewBag.MenuLayoutName to decide which menu to use. The most efficient way is to simply create partial views so you can render the menu as follows:

@{ Html.RenderPartial(ViewBag.MenuLayoutName); }

However, take note of the call to IsValidMenuLayoutName! Otherwise people could put the name of any valid partial view in there and get it rendered where you expect your menu to appear.

In your links where you want to allow the user to select the various menu layouts, change your link to the page to specify the name of the layout to use.

<a href="/Index?MenuLayoutName=RedLayout">Use Red Menu</a>

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101604

Using a VERY primitive approach, you can create buttons essentially linking to itself:

<a href="@(Request.RawUrl)?menu=foo">Foo Menu</a>
<a href="@(Request.RawUrl)?menu=bar">Bar Menu</a>

(Or use logic to show either/or based on what's visible) Then modify your _Layout.cshtml to render what's provided:

@{
  String menu = (String)Request.Params["menu"] ?? "foo";
  if (menu == "foo"){
    /* Foo menu render */
  } else {
    /* bar menu render */
  }
}

Then it's just a round-trip to the same URL. Again, if they landed on the page via POSTed information, you'll lose that. Also, I didn't add logic to test if menu already existed in the request, but you should.

Upvotes: 1

Related Questions