Asp.net 将一些服务器代码从我的视图移动到HtmlHelper
我的观点如下:Asp.net 将一些服务器代码从我的视图移动到HtmlHelper,asp.net,asp.net-mvc-3,Asp.net,Asp.net Mvc 3,我的观点如下: window.location = '@Html.Raw(Url.Action("SearchAffaires","Search", (SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]))' window.location = '@Html.NavigateSearchPage()' 我如何使用辅助对象来转换它?比如: 我认为: window.location = '@Html.Raw(Url.Action("Sea
window.location = '@Html.Raw(Url.Action("SearchAffaires","Search", (SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]))'
window.location = '@Html.NavigateSearchPage()'
我如何使用辅助对象来转换它?比如:
我认为:
window.location = '@Html.Raw(Url.Action("SearchAffaires","Search", (SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]))'
window.location = '@Html.NavigateSearchPage()'
在HtmlHelpers.cs中:
public static string NavigateSearchPage(this HtmlHelper helper)
{
// what do I have to code here?
}
或者有更好的方法吗?如果您想要生成的链接,请让您的助手返回一个,使用
UrlHelper
而不是HtmlHelper
ans,只需调用您在视图中使用的相同方法:
public static HtmlString NavigateSearchPage(this UrlHelper helper)
{
return helper.Action("SearchAffaires","Search",
(SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]);
}
这是你必须走的路
public static string NavigateSearchPage(this HtmlHelper helper)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext)
return helper.Raw(urlHelper.Action("SearchAffaires","Search", (SearchCriteriaAffaire)helper.ViewContext.HttpContext.Session["SearchCriteriaAffaire"])));
}
在这种情况下,UrlHelper扩展比HTML helper更有意义 你可以这样做:
public static string SearchPage(this UrlHelper helper)
{
return helper.Action("SearchAffaires",
"Search",
(SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]);
}
视图:
助手上的结束括号太多。上面的操作函数。@Chris-已修复,谢谢。我刚刚复制/粘贴了OP的问题:)没问题。我想是的。原始的有一个Url.Raw函数,它是额外的来源;来自上面的helper.Action。这正是我想要的:)