Instantiate a helper class but not in view

被刻印的时光 ゝ 提交于 2019-12-11 04:42:50

问题


I need a way to instantiate a class thats supposed to help me with some querystring-building when it comes to my links in the view, and I cant use this methods that i require as static methods since that would cause the querystringbuilder to keep data during the whole life-time of the application (which would cause some serious problems)

So my question to you guys is, Is it possible to some how be able to instantiate the class/object that i require but not in the actual view itself?

SO to keep the question simple.. is there anyway that I could do something like:

@MyInstantiatedObject.DoStuff()

in my view with out doing this before in my view:

@{
    var MyInstantiatedObject = new MyClass()

}

I do get that I some where some how will need to instansiate the object, but my question is if its possible to do it in some other manner (like telling the web.config to handel it..or using some app_code @helper magic or something)

Thanks in advance!


回答1:


What you are trying to achieve goes against the philosophy of MVC. If you want to keep the query string data between the actions, you can create your custom ActionLink html helper like this:

public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper htmlHelper, 
    string linkText, string actionName)
{
    var routeValueDictionary = new RouteValueDictionary();

    return htmlHelper.ActionLinkWithQueryString(linkText, 
        actionName, routeValueDictionary);
}

public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper htmlHelper, 
   string linkText, string actionName, RouteValueDictionary routeValues)
{
    var queryString = HttpContext.Current.Request.QueryString;

    if (queryString.Count > 0)
    {
        foreach (string key in queryString.Keys)
        {
            routeValues.Add(key, queryString[key]);
        }
    }

    return htmlHelper.ActionLink(linkText, actionName, routeValues);
}

You can also create a custom RedirectToAction method in your Controller or in a Controller Extention like this:

private RedirectToRouteResult RedirectToActionWithQueryString(string actionName)
{
    var queryString = Request.QueryString;
    var routeValues = new RouteValueDictionary();

    foreach (string key in queryString.Keys)
    {
        routeValues.Add(key, queryString[key]);
    }

    return RedirectToAction(actionName, routeValues);
}


来源:https://stackoverflow.com/questions/17466682/instantiate-a-helper-class-but-not-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!