如何从MVC中的javascript调用服务器端函数? [英] How to call a server-side function from javascript in MVC?
问题描述
我正在MVC应用程序中进行修改,以禁止用户在单个会话中打开多个选项卡/窗口.我正在参考
I am doing amendments in my MVC application in order to disallow users to open more than one tab/ window within a single session. I am taking reference of this article (click here) in order to do that. This article is written for asp.net whereas I need to implement this feature for ASP.NET MVC. I think all this should be possible in MVC, however, I am not sure what should I do to re-write this
if(window.name != "<%=GetWindowName()%>")
GetWindowName()是我在Controller中创建的函数,它从Session对象返回"WindowName"键的值.如何在上面的javascript中读取其值?
GetWindowName() is a function I have created in my Controller, and it returns a value of "WindowName" key from Session object. How can I read its value in above javascript?
推荐答案
您可以为此编写控制器方法:
You can write a controller method for that:
public ActionResult GetWindowName()
{
Session["WindowName"] =
Guid.NewGuid().ToString().Replace("-", "");
return Json(Session["WindowName"].ToString());
}
然后通过ajax调用它:
Then call it through ajax:
$.get('@Url.Action("GetWindowName")', function(data){
if(window.name != data) {
// do what you need to do here
}
})
这篇关于如何从MVC中的javascript调用服务器端函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!