views:

805

answers:

3

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?

+5  A: 

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.

karim79
So I've implemented this:$('#refreshGrid').load('/Client/GetAttachments?id=' + clientID);My client controller looks like this:public ActionResult GetAttachments(int id){ // Some logic... return PartialView("~/Views/Client/ClientAttachmentGridView.ascx", files);} alert($('#refreshGrid')) is giving me an object and alert(clientID) gives me what I expect. The controller is not getting hit (otherwise I'd see some web service calls from fiddler). The annoying thing is I'm not seeing any error messages.
RailRhoad
Oooh, I take that back. I am getting a 500 in fiddler:The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetAttachments(Int32)' in 'CommercialLendingPlatform.Controllers.ClientController'. To make a parameter optional its type should be either a reference type or a Nullable type.<br>Parameter name: parameters
RailRhoad
Marvelous! I needed to make that a Client/GetAttachments/clientID instead! Forgot about the url routing for a second. Thanks everyone!
RailRhoad
+1  A: 

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);
});
Dan Esparza
+1  A: 
$.ajax("MyController/MyAction", function(data) {
    alert(data);
});

This is a really basic example; you just call the controller using AJAX and then you can pop the data into the DOM or do something else with it.

Sohnee