Skip to content Skip to sidebar Skip to footer

Mvc3 Calling Controller Method From Javascript

In MVC3. I have a button class'open-deleteRowDialog' when i click on it goes to this javascript: $(document).on('click', '.open-DeleteRowDialog', function () { var pwd=

Solution 1:

Make an ajax call to your controller action method. You may use $.get method like below.

$(function(){
   $(document).on("click", ".open-DeleteRowDialog", function () { 
      var pwd="";
       $.get("@Url.Action("Yourcontroller","GeneratePsw")",function(data){
           pwd=data;
           //now do whatever you want with pwd variable;
       });    
    })
 });

$.get is a short form of $.ajax method with type HTTP GET.

If you have trouble like cached data in the response, you may add a unique timestamp in your get call so that you won't get the cached result. You may use $.now method.

 $.get("@Url.Action("Yourcontroller","GeneratePsw")?"+$.now(),function(data){
    // to do : do something with result
 });

Another way is to set the cache property value to false in ajaxSetup method. But this will be applicable to all ajax calls.

Solution 2:

Use jQuery ajax and call the controller method directly as a url

$(document).on("click", ".open-DeleteRowDialog", function () { 
    var pwd="";
    $.get('Yourcontroller/GeneratePsw', function(data){
        pwd=data;
        //now do whatever you want with pwd variable;
    });    
})

Post a Comment for "Mvc3 Calling Controller Method From Javascript"