views:

61

answers:

2

Let's say I have a simple ASP.NET MVC site with two views. The views use the following routes: /Foo and /Foo/Bar.

Now let's say I want to use the URL to specify (just for the sake of example) the background color of the site. I want my routes to be, for instance, /Blue/Foo or /Green/Foo/Bar.

Also, if I call Html.ActionLink from a view, I want the Blue or Green value to propagate, without having to be passed in. So, e.g., if I call Html.ActionLink("Bar", "Foo") from /Blue/Foo, I want /Blue/Foo/Bar to come back.

How best can I do this?

(Forgive me if I'm missing an existing post. This is hard for me to articulate concisely, so I'm not quite sure what to search for.)

+1  A: 

Check out this article, specifically about ActionLink

http://stephenwalther.com/blog/archive/2009/03/03/chapter-6-understanding-html-helpers.aspx

Note how the parameters work. You could pass the color with in the routeValues param, using a value from your model.

Dan Giralte
I'm looking to do this without having to pass a parameter to Html.ActionLink.
joshjs
+1  A: 

Personally I think this would really be way to "hacky" to implement and maintain in the long term.

Why don't you just use Url Parameters instead?

Example - A concrete implementation would be something like this:

public ActionResult BackGroundColorChangerAction(string color = "") { // <- Providing a default value if no value was defined
    ViewData["backgroundColor"] = color; // Or do some processing first

    return View();
}

Now we need to display the value in our view. Thanks to ViewData we can easily feed our views with the correct data:

...
<body>
    <div>
        <h2>Your Current Color: <b><%: ViewData["backgroundColor"] %></b></h2>

        <%: Html.ActionLink("Red", "BackGroundColorChangerAction", new { color = "red" }) %><br />
        <%: Html.ActionLink("Green", "BackGroundColorChangerAction", new { color = "green" }) %><br />
        <%: Html.ActionLink("Blue", "BackGroundColorChangerAction", new { color = "blue" }) %><br />
    </div>
</body>
...

You can now do absolutely everything with your received ViewData["backgroundColor"] value. Wire it up with JavaScript and you can easily do the color switches on your html elements.

I did it with fixed string values for the links and the optional parameters, but you can easily setup an Enum or a database table that contains this data.

Shaharyar
Clarified this in the original question: I'd like to not have to pass the value into Html.ActionLink. I'm considering using a session variable and a custom Helper method, but I'm looking for other ideas.
joshjs