How to construct URLs in MVC?

I am using Url.RouteUrl to create a URL to return to my user.

var path = Url.RouteUrl(new RouteValueDictionary()
            {
                { "controller", "Home"},
                {"action", "myaction"},
                {"area" , "myarea"},
            });

This returns me a nice URL with myarea/home/myaction

If I need to add an extra param to it, say like myarea/home/myaction?param1=abc, how can that be done ?

I tried

var param1Value = "abc";
var path = Url.RouteUrl(new RouteValueDictionary()
            {
                { "controller", "Home"},
                {"action", "myaction"},
                {"area" , "myarea"},
                new {param1 = param1Value },
            });

This seems like not the way to be.

Can any one suggest some way to do this ?

Upvotes: 0

Views: 89

Answers (3)

dama
dama

Reputation: 306

Try this:

    Url.Action("myAction","Home", new {area="myarea", param="paramvalue"});

Upvotes: 1

Durga Nunna
Durga Nunna

Reputation: 51

Hope this helps:

return (new RedirectToRouteResult(
                    new System.Web.Routing.RouteValueDictionary(
                        new
                        {
                            controller = "Home",
                            action = "myAction",
                            area = "myArea"
                        })));

If you want to add a param to it, you may add/modify the route map in the Route Config file. Once the new key is added, the value can be specified in the above code.

Upvotes: 0

Found out an elegant way of doing this.

var myDesiredUrl = FetchDomainUri();

myDesiredUrl.Path = Url.RouteUrl(new RouteValueDictionary()
{
    { "controller", "Home" },
    { "action", "myAction" },
    { "area" , "myArea" },
});

myDesiredUrl.QueryString.Add("myParam1", param1Value);

Upvotes: 0

Related Questions