How to call a server-side function from javascript in MVC?

泪湿孤枕 提交于 2021-02-10 05:45:53

问题


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() 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?


回答1:


You can write a controller method for that:

public ActionResult GetWindowName()
{
  Session["WindowName"] = 
    Guid.NewGuid().ToString().Replace("-", "");
  return Json(Session["WindowName"].ToString());
}

Then call it through ajax:

$.get('@Url.Action("GetWindowName")', function(data){
    if(window.name != data) {
        // do what you need to do here
    }
})



回答2:


You can use ajax for that (jQuery):

$.get('@Url.Action("GetWindowName")', function(result){
    if(window.name != result)
    //...
});

This is razor syntax...



来源:https://stackoverflow.com/questions/16099074/how-to-call-a-server-side-function-from-javascript-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!