如何在ASP.NET MVC页面周期调用一个函数*只有一次* [英] How to call a function *only once* in ASP.NET MVC page cycle

查看:98
本文介绍了如何在ASP.NET MVC页面周期调用一个函数*只有一次*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC的Web应用程序,并有我需要的只有一次,当调用加载页面的功能。现在我有这个功能可以从OnActionExecuted一个基本的控制器被调用。

I have an ASP.NET MVC web app and have a function that I need to call when the page loads only once. Right now I have the function being called from a base controller OnActionExecuted.

我遇到的问题是,这个函数被调用多次 - 一次页面,并针对不同的阿贾克斯则多次呼吁,我在页面上。我试图把在控制器初始化函数,但是这也被称为对每个Ajax调用一个控制器动作。那么,有没有在ASP.NET MVC页面周期某些功能时,一个页面被请求(GET),而不是对所有的Ajax调用(POST)中,只有被调用?我能想到的是把所有独立的控制器Ajax调用不从基本控制器继承,但的唯一的事情,必须有一个更好的解决方案。

The issue I'm having is that this function is called multiple times - once for the page, and then multiple times for different ajax calls that I have on the page. I've tried putting the function on Controller Initialize but this is also called for each ajax call to a controller action. So is there some function in the ASP.NET MVC page cycle that only gets called when a page is requested (GET) and not for all of the ajax calls (POST)? The only thing I can think of is putting all of the ajax calls in separate controllers that don't inherit from the base controller but there must be a nicer solution.

推荐答案

根据你如何做你的AjaxRequests,你可以使用类似以下内容:

Depending on how you're doing your AjaxRequests you could use something like the following:

public ActionResult Index()
{
    if (!Request.IsAjaxRequest())
    {
        LoadConfiguration();
    }

    // Rest of Action method (snip)...
}

这工作,如果,例如,你正在与 jQuery JavaScript库它发送一个特殊令牌进行阿贾克斯服务器表明它是一个Ajax调用(我敢肯定,其他图书馆做到这一点)。这可能会更好,以防万一有人更改JavaScript code执行GET Ajax请求。

This works if, for instance, you're performing Ajax with the jQuery JavaScript library which sends a special token to the server to indicate that it's an Ajax call (I'm sure other libraries do this). This might be better just in case someone changes the JavaScript code to perform GET Ajax requests.

您提到一件事确实激起我的兴趣,虽然的我遇到的问题是,这个函数被调用多次的 - 其实'的技术上的'这是不正确。它仅获取调用一次....每个请求,所有这些Ajax调用被视为由服务器单独的请求,因为如果用户经由web浏览器请求的网页。这听起来像你真正需要的是一种网页HTTP请求来区分和Ajax HTTP请求,因此上述溶液。

One thing you mentioned does intrigue me though "The issue I'm having is that this function is called multiple times" - actually 'technically' this is not true. It IS only getting called once....per request, all those Ajax calls are treated as separate requests by the server, as if the user is requesting a page via the web browser. It sounds like what you really need is a way to differentiate between web page HTTP Requests, and Ajax HTTP Requests, hence the above solution.

这篇关于如何在ASP.NET MVC页面周期调用一个函数*只有一次*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆