更新视图ASP NET MVC 3.0

时间:2011-01-26 19:56:29

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

如何仅使用控制器刷新视图。是否有类似的内容?

public ActionResult Index()
{

     [Controller(Update = 10)]

}

1 个答案:

答案 0 :(得分:3)

创建一个“AutoRefresh”操作属性,用于注入元刷新标记:

public class AutoRefreshAttribute : ActionFilterAttribute
{
    public const int DefaultDurationInSeconds = 300; // 5 Minutes

    public AutoRefreshAttribute()
    {
        DurationInSeconds = DefaultDurationInSeconds;
    }

    public int DurationInSeconds
    {
        get;
        set;
    }

    public string RouteName
    {
        get;
        set;
    }

    public string ControllerName
    {
        get;
        set;
    }

    public string ActionName
    {
        get;
        set;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        string url = BuildUrl(filterContext);
        string headerValue = string.Concat(DurationInSeconds, ";Url=", url);

        filterContext.HttpContext.Response.AppendHeader("Refresh", headerValue);

        base.OnResultExecuted(filterContext);
    }

    private string BuildUrl(ControllerContext filterContext)
    {
        UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
        string url;

        if (!string.IsNullOrEmpty(RouteName))
        {
            url = urlHelper.RouteUrl(RouteName);
        }
        else if (!string.IsNullOrEmpty(ControllerName) && !string.IsNullOrEmpty(ActionName))
        {
            url = urlHelper.Action(ActionName, ControllerName);
        }
        else if (!string.IsNullOrEmpty(ActionName))
        {
            url = urlHelper.Action(ActionName);
        }
        else
        {
            url = filterContext.HttpContext.Request.RawUrl;
        }

        return url;
    }
}

然后像这样使用它:

[AutoRefresh(DurationInSeconds = 10)]
public ActionResult Index()
{

}