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.

2 Answers 2

3

Are you looking for something like this:

string url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I generate the url in service class which is not aware of MVC. "YourAction" is hardcoded, I do not want that.
how does the service class know which action method to use for url generation ?
at the moment the email templates get the created url injected. The url are created by hand... not refactoring safe ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.