Asp.net mvc 5 ASP.NET在ViewModel中使用UrlHelper
当我构建一个viewmodel时,我正试图为一个web应用程序强键入一些URL(比如它) 所以我有点像:Asp.net mvc 5 ASP.NET在ViewModel中使用UrlHelper,asp.net-mvc-5,Asp.net Mvc 5,当我构建一个viewmodel时,我正试图为一个web应用程序强键入一些URL(比如它) 所以我有点像: new MyModel { Text = "Foo", Url = new UrlHelper(Request.RequestContext).Action("MyAction") } 这在控制器方法中工作得很好,但我有另一种情况,我没有收到Request.Context,因为它在另一个类中被调用 有没有其他方法可以做到这一点,这样我
new MyModel {
Text = "Foo",
Url = new UrlHelper(Request.RequestContext).Action("MyAction")
}
这在控制器方法中工作得很好,但我有另一种情况,我没有收到Request.Context,因为它在另一个类中被调用
有没有其他方法可以做到这一点,这样我就不会使用“魔法字符串”和/或依赖上下文对象了?使用引用
HttpContext.Current
它是从system.web
派生的。下面的代码将在应用程序中的任何位置工作
UrlHelper objUrlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
objUrlHelper.Action("About");
例如:
public class MyViewModel
{
public int ID { get; private set; }
public string Link
{
get
{
UrlHelper objUrlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
return objUrlHelper.Action("YourAction", "YourController", new { id = this.ID });
}
}
public MyViewModel(int id)
{
this.ID = id;
}
}