Nirman
Nirman

Reputation: 6783

How to call a server-side function from javascript in 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() 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?

Upvotes: 3

Views: 3987

Answers (2)

von v.
von v.

Reputation: 17108

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
    }
})

Upvotes: 5

karaxuna
karaxuna

Reputation: 26930

You can use ajax for that (jQuery):

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

This is razor syntax...

Upvotes: 4

Related Questions