Reputation: 11885
in my asp.net mvc3 web site, I use Url.Action
in the view to generate url.
@Url.Action("Profile", "Users", new { @Id = Model.UserId, name = Model.NickName })
now, in one of my helper class, I need to do the same. but get this error message, "The name 'Url' does not exist in the current context.
is there another function I can use to generate url?
Upvotes: 3
Views: 7023
Reputation: 39014
You can use this code anywhere, and you don't need the UrlHelper or the context:
RouteValueDictionary rvd = new RouteValueDictionary
{
{"controller", "ControllerName"},
{"action", "ActionName"},
{"area", ""}
};
VirtualPathData virtualPathData
= RouteTable.Routes.GetVirtualPath(null, new RouteValueDictionary());
return virtualPathData.VirtualPath;
This will only work if the property 'HttpContext.Current' is not null, which is true for code running in a web app. If you don't supply the first parameter for GetVirtualPath the system will find use the context returned by the aforesaid static property.
So it's still true that you can use this method to get the URL without supplying the context.
The context is always necessary because it has the information of the server, and virtual directoy if present, in which the app is running.
Upvotes: 1
Reputation: 3026
@Url in your example is an instance of UrlHelper
class. You can create an instance of it and use in any class like in the example below, but you need to have an access to the RequestContext
(named context in my example) of the corresponding View.
var urlHelper = new UrlHelper(context);
string absUrl = urlHelper.Action("ActionName",
"ControllerName", null, Request.Url.Scheme);
Upvotes: 12
Reputation: 6607
You can't use a Razor helper outside of a Razor view, @Url
is a Razor helper and is only scoped to the view page. Not inside a .net class file.
Try this example in your class file
var urlHelper = new UrlHelper(context);
string absUrl = Url.Action("Users", "Users", new { Id = UserId, name =.NickName }, Request.Url.Scheme);
Or from a controller just use
return RedirectToAction("Profile", "Users", new { @Id = Model.UserId, name = Model.NickName })
Upvotes: 3