将一些服务器代码从我的视图移动到HtmlHelper

时间:2011-05-04 08:11:38

标签: asp.net asp.net-mvc-3

我的观点中有以下声明:

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?
    }

或许有更好的方法?

3 个答案:

答案 0 :(得分:1)

如果您想要生成的链接,请让您的助手返回HtmlString,使用UrlHelper代替HtmlHelper,只需调用您在视图中使用的相同方法:

public static HtmlString NavigateSearchPage(this UrlHelper helper)
{
    return helper.Action("SearchAffaires","Search", 
        (SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]);
}

答案 1 :(得分:0)

这就是你必须走的路。

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"])));
}

答案 2 :(得分:0)

在这种情况下,UrlHelper扩展比HTML帮助更有意义。

你可以这样做:

    public static string SearchPage(this UrlHelper helper)
    {
        return helper.Action("SearchAffaires",
               "Search", 
               (SearchCriteriaAffaire)Session["SearchCriteriaAffaire"]);
    }

查看:

window.location = '@Html.Raw(Url.SearchPage())';