且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET MVC页面周期调用一个函数*只有一次*

更新时间:2022-12-27 13:16:55

根据你如何做你的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.