How to save a useful value in an ASP.NET MVC URL and make it common?

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

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

Also, if I call Html.ActionLink from the view, I want the Blue or Green value to propagate without the need to pass it. So, for example, if I call Html.ActionLink ("Bar", "Foo",) from / Blue / Foo, I want / Blue / Foo / Bar to return.

How can i do this?

(Forgive me if I am missing an existing message. It is difficult for me to formulate briefly, so I'm not quite sure what to look for.)

+3
source share
2 answers

Check out this article, in particular about ActionLink.

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

Notice how the options work. You can pass the color with the routeValues ​​parameter using the value from your model.

+2
source

Personally, I think that this will really be a way to “hack” for implementation and support in the long run.

Why don't you just use URL parameters?

Example. A specific 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();
}

. ViewData :

...
<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>
...

ViewData [ "backgroundColor" ]. JavaScript, html.

, Enum , .

+1

Source: https://habr.com/ru/post/1747084/


All Articles