2

I have such a url:

www.test.com/MyAreaName/MyControllerName/MyAction?key1=value&key2=value

I need a method like:

string generatedUrlWithQueryParams = Url.Action<MyController>(x => x.MyAction(MyViewModel));

I need to call the above method from a .cs class NOT from razor html file.

How can I do that? I heard of asp.net mvc futures but I can not find the appropriate method or namespace to use that method.

Pascal
  • 12,265
  • 25
  • 103
  • 195

2 Answers2

3

Are you looking for something like this:

string url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
JPG
  • 145
  • 9
1

If you have the Request available(it is available in your controller actions), you can use the UrlHelper class.

var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder .Action("YourAction", new YourViewModel { Age = 44, Code = "Test"});

or

var url = urlBuilder .Action("YourAction", "YourController",
                                           new YourViewModel { Age = 44, Code = "Test"});

Assuming YourViewModel has Age and Code property and you need those as the route values of the generated url.

If you are invoking this code from another class, you may pass the RequestContext to that from your controller/action.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I generate the url in service class which is not aware of MVC. "YourAction" is hardcoded, I do not want that. – Pascal Jan 26 '16 at 19:44
  • how does the service class know which action method to use for url generation ? – Shyju Jan 26 '16 at 20:07
  • at the moment the email templates get the created url injected. The url are created by hand... not refactoring safe ;-) – Pascal Jan 26 '16 at 20:11