IAmGroot
IAmGroot

Reputation: 13855

ASP.NET MVC3: Passing cookies to a helper method

What I am trying to do is basically set the URL to take you to a webpage that uses your last known parameters.

  1. You visit a page with parameter show all set false, so it shows non in list.

  2. You then change show all to true. So it shows all in list.

  3. An hour later you revisit that page. It knows you last had show all to true.:

MR Controller - Index:

HttpCookie mr1 = new HttpCookie("MR1", "test");
Request.Cookies.Add(mr1); // Save all parameters used in cookies. (WORKING).

View with button:

<input type="button" class="cancel" value="Cancel" onclick="location.href='@MyNS.Helpers.HtmlHelper.MRUrl(Request.Cookies)'">

MyNS.Helpers.HtmlHelper:

public static String MRUrl(COOKIES? myCookie)
    {
        //If not null, add to object array.
        myCookie["MR1"].Value;
        myCookie["MR2"].Value;

        return @Url.Action("Index", "MR"); // Plus non null variables as parameters.
    }

What I cant do is access any Cookies via my helper. Nor do I know if this is the best way to do it. I just want to take out the cookie info that has the parameters used, and use it to build the required URL.

There will be 6-7 different index page variable storing methods.

Upvotes: 1

Views: 2147

Answers (1)

Chris
Chris

Reputation: 28064

I think you want a UrlHelper extension like this:

public static class UrlHelperExtensions
{
    private static string GetCookieOrDefault(HttpRequestBase request, string name)
    {
        return request.Cookies[name] == null ? "" : request.Cookies[name].Value;
    }

    public static string MRUrl(this UrlHelper url)
    {
        var request = url.RequestContext.HttpContext.Request;

        return url.Action("Index", "MR", new
        {
            mr1 = GetCookieOrDefault(request, "MR1"),
            mr2 = GetCookieOrDefault(request, "MR2"),
            mr3 = GetCookieOrDefault(request, "MR3")
        });
    }
}

You can then use this in any view like so:

<a href="@Url.MRUrl()">link text</a>

Or in the case of your button...

<input type="button" class="cancel" value="Cancel" onclick="location.href='@Url.MRUrl()';">

Edit: You'd need to import the namespace of the UrlHelperExtensions class before using the helper, obviously.

Upvotes: 3

Related Questions