如何从action属性获取视图文本

时间:2016-12-28 07:16:50

标签: c# .net asp.net-mvc asp.net-mvc-4 view

我需要从某个动作属性中获取视图文本(不是渲染的html)。

例如:

View (someview ) text :  Hello @Name @Surname

[ActionFilter]
public SomeViewAction()
{
    return View(someview,someModel);
}

public class ActionFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutedContext filterContext)
    {
        //here I need get text "Hello @Name @Surname"
    }
}

1 个答案:

答案 0 :(得分:0)

如果你有这样的动作过滤器:

public class ActionFilterAttribute : FilterAttribute, IResultFilter
{
    public string ViewName { get; set; }

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //throw new NotImplementedException();
    }

    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var viewResult = filterContext.Result as ViewResult;
        if(viewResult != null)
        {
            var viewName = string.IsNullOrEmpty(ViewName) ? (string.IsNullOrEmpty(viewResult.ViewName) ? filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString() : viewResult.ViewName) : ViewName;
            if(!string.IsNullOrEmpty(viewName))
            {
                var viewEngine = ViewEngines.Engines.FindPartialView(filterContext.Controller.ControllerContext, viewName);
                var razorView = viewEngine.View as RazorView;
                if (razorView != null)
                {
                    using (var reader = new StreamReader(filterContext.HttpContext.Server.MapPath(razorView.ViewPath)))
                    {
                        var markups = reader.ReadToEnd();
                    }
                }
            }
        }
    }
}

您可以在控制器操作中应用过滤器:

    [ActionFilter]
    public ActionResult SomeView()
    {
        //var someview = "SomeView";
        var somemodel = default(object);
        return View(somemodel);
    }