如何在ASP.Net MVC 3 razor视图中使用Ajax和Jquery加载页面部分?

Mah*_*eep 4 jquery razor asp.net-mvc-3

我正在使用Razor视图引擎和Jquery的ASP.Net MVC 3网站

在主页(或任何页面)我想使用ajax加载内容部分,比如iGoogle.

我的意思是页面加载

  • 我想调用一些HttpGet动作方法,每个方法都返回一些Html内容

  • 直到我得到回应这些Div显示"加载"图形.

我知道Ajax.BeginForm和Ajax.ActionLink,但在这两种情况下我都需要点击一些UI元素; 我不知道如何在页面加载/ document.ady上使用它们?

即使我得到一些方向而不是确切/完整的代码,我也会感激不尽.

use*_*606 9

好的,让我们给你一些方向,我将在jquery中显示一些代码,因为它很容易.我们走吧.

HTML

<div id="SomeContent"> </div>
Run Code Online (Sandbox Code Playgroud)

在你看来

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

在JavaScript库文件中

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.
}
Run Code Online (Sandbox Code Playgroud)

你的服务器端代码

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

额外的想法:

  • 这个粗略的代码将局部视图加载到div中.当dom准备好时,asychonous呼叫开始.
  • 有关jquery ajax文档,请参阅http://api.jquery.com/jQuery.ajax/
  • 我喜欢使用spin.js来显示加载图标,因为它非常容易和小.