Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Url in MVC from Code Behind

Lets say i`m in an action method and i want to generate a string like this :

http://www.myhost.com/Home/Index?Id=1

i want to save this to DB so i was wondering if there is any formal way to generate it instead of building it up myself.

I`m using MVC3

thanks in advance.

like image 937
Stacker Avatar asked Dec 17 '11 16:12

Stacker


People also ask

How do you create a URL for a controller?

UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u. Action("About", "Home", null);

What is URL RouteUrl?

RouteUrl(String, RouteValueDictionary, String, String) Generates a fully qualified URL for the specified route values by using the specified route name, protocol to use, and host name.

What is difference between HTML ActionLink and URL action?

There is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is URL pattern in MVC?

URL patterns for routes in MVC Applications typically include {controller} and {action} placeholders. When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler.


1 Answers

You could use the Url property of the controller:

public ActionResult Foo()
{
    string url = Url.Action("Index", "Home", new { id = 1 });
    // TODO: save to DB
}

and if you need an absolute url just use the proper overload:

string url = Url.Action("Index", "Home", new { id = 1 }, "http");
like image 104
Darin Dimitrov Avatar answered Sep 29 '22 05:09

Darin Dimitrov