Asp.net mvc 3- get the current controller instance (not just name)

前端 未结 2 501
日久生厌
日久生厌 2020-12-09 04:10

I know how to get the current controller name

HttpContext.Current.Request.RequestContext.RouteData.Values[\"controller\"].ToString();

But i

2条回答
  •  不思量自难忘°
    2020-12-09 05:02

    Someone will have to correct me if what I am doing is detrimental to the whole Asp.Net page life cycle / whatever but surely you can do this:

    In controller

    ViewBag.CurrentController = this;
    

    In view

    var c = ViewBag.CurrentController;
    var m1 = BaseController.RenderViewToString(c, "~/Views/Test/_Partial.cshtml", null);
    

    In my case, I had a base controller that all controllers extend. In that base controller lived a static method called RenderViewToString and it required a controller. Since I figured I could just instantiate a new instance of an empty controller at this point for c, I just sent it to the view in the lovely ViewBag container that exists in the world of Asp.Net MVC. For reasons I could not go into now, I could not retrieve the string in the controller and send just that back to the view (this was what I had done earlier before requirements changed).

    The reason I have done it this way is in other languages like PHP and JS, there are similar simple ways to transfer classes around.

提交回复
热议问题