Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load page sections using Ajax and Jquery in ASP.Net MVC 3 razor view?

I am working on ASP.Net MVC 3 website which uses Razor view engine and Jquery

On homepage (or any page for that matter) I want to load sections of content using ajax, something like iGoogle.

I mean on page load

  • I want to call some HttpGet action methods each of which returns some Html content

  • Until I get response these Div's showing "loading" graphics.

I am aware of Ajax.BeginForm and Ajax.ActionLink but in both the cases I need to click some UI element; I do not know how to use them on page load/ document.Ready?

I will be thankful even if I get some direction and not exact/complete code.

like image 563
Maheep Avatar asked Jan 14 '23 00:01

Maheep


1 Answers

Okay, lets give you some direction, I'm going to show some code in jquery because its easy enough. lets go.

Html

<div id="SomeContent"> </div>

In your view

$(function(){ // this runs on on page load
    LoadData('#SomeContent', @Url.Action("ActionName","ControllerName"));
});

in a javascript library file

function LoadData(target, url){
  $.ajax({  
   beforeSend: startAnimation(target),
   url : url,
   success : function(result){ $(target).html(result); },
   complete  : stopAnimation(target)   
});
}

function startAnimation(target){
  //..add a loading image on top of the target  
}

function stopAnimation(target){
  // remove the animation gif or stop the spinning, etc.
}

your server side code

public ActionResult ActionName() {
    ... do things to get your model populated ...
    return PartialView("SomeView", yourmodel);
}

additional thoughts:

  • this rough code loads a partial view into a div. The asychonous call begins when the dom is ready.
  • see http://api.jquery.com/jQuery.ajax/ for jquery ajax documentation
  • i like to use spin.js to show a loading icon becuase it is so darn easy and small.
like image 154
monkeyhouse Avatar answered Jan 21 '23 11:01

monkeyhouse