Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery To Call A Controller Action

I have a nice page that does everything I need. However one of the elements (a partial page) takes a few seconds longer then I'd like to load. So what I'd like to do is to show the page without this partial first but show a "loading" gif in its place. Then in my jquery...

$(document).ready(function() {

   // Call controller/action (i.e. Client/GetStuff)

});

I'd like to call my controller action that returns a PartialView and updates my div contents. It basically calls the partial load asynchronously on load. I could do this just fine with an ActionLink until it get's to the point where I'd like to do it onload. If I use jQuery for the onloand type call, can I even return a PartialView?

like image 253
RailRhoad Avatar asked Aug 26 '09 12:08

RailRhoad


People also ask

How can we call controller action using jQuery in ASP NET MVC?

The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX called is made to the Controller's action method. The URL for the jQuery AJAX call is set to the Controller's action method i.e. /Home/AjaxMethod.


2 Answers

Simply use $.load:

$(document).ready(function() {    
   $('#myDiv').html('<img src="loading.gif"/>')
              .load('Client/GetStuff');   
});

That will replace the contents of div id="myDiv" with your loading indicator, and then inject the output of Client/GetStuff into it.

like image 132
karim79 Avatar answered Sep 18 '22 12:09

karim79


I believe you can. I've used jQuery to get JSON from an ASP.NET MVC controller before, and it's one of the most pleasant ways I've found to get data to the client.

I'm sure getting a partial view might be as simple as using the jQuery 'load', 'get' or 'post' methods:

Using Load:

$("#feeds").load("test.aspx");

Using Get:

$.get("test.aspx", function(data){
  alert("Data Loaded: " + data);
});

Using Post:

$.post("test.aspx", function(data){
  alert("Data Loaded: " + data);
});
like image 33
Dan Esparza Avatar answered Sep 22 '22 12:09

Dan Esparza