Ajax技术显著加快了Web应用程序的速度。另外,视觉效果方面也有提升。大家都同意,每次点击按钮时整个页面都会被刷新这一点不太友好。如果你的网速不是很快,那么这个过程会很烦人,因为所有的元素都会先消失,再慢慢重新出现。如果只刷新一部分页面,那就美滋滋了。而这正是Ajax所提供的。该脚本向服务器发送一个请求,以更新所需的部分信息。然后,脚本将更新的数据插入页面上的正确位置。
在这个页面中,我想用一个简单的方法通过Ajax更新ASP .Net MVC项目中的信息。这种方法被称为“unobtrusive Ajax” - Microsoft Unobtrusive Ajax。其底线是使用Unobtrusive库,并且,辅助程序允许你使用Ajax而无需编写任何JavaScript代码。这个例子会非常简单,适合初学者。那么,我们开始吧。
要在一个MVC项目中使用FastReport.Net报表生成器自带的WebReport组件,你需要调整一些配置。即,编辑Web.Config文件并添加必要的库。
将FastReport和FastReport.Web库添加到你的项目中。
在Web.config中添加处理句柄,它位于项目的根目录中:
在位于Views文件夹中的Web.config文件中添加命名空间。
在_Layout.cshtml文件的
部分添加脚本和样式:@WebReportGlobals.Scripts()
@WebReportGlobals.Styles()
现在我们切换到HomeController.cs。在这里,我们放置业务逻辑:
我已经创建了全局报表对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FastReport.Web;
using System.Web.UI.WebControls;
using System.Globalization;
using WebLocalization.Models;
namespace WebLocalization.Controllers
{
public class HomeController : Controller
{
private WebReport webReport = new WebReport(); // report object is available within the class
private string report_path = "J:\\Program Files (x86)\\FastReports\\FastReport.Net\\Demos\\Reports\\"; //reports folder
public ActionResult Index()
{
SetReport(); //method of loading report and DB
ViewBag.WebReport = webReport; //pass the Web Report into the View
return View();
}
public void SetReport()
{
System.Data.DataSet dataSet = new System.Data.DataSet(); //create data set dataSet.ReadXml(report_path + "nwind.xml"); //Load xml database webReport.Report.RegisterData(dataSet, "NorthWind"); // register the data source in the report object
webReport.Report.Load(report_path + "Simple Interactive.frx"); //load the report into WebReport object
webReport.Width = Unit.Percentage(100);
webReport.Height = Unit.Percentage(100);
}
如你所见,Index方法只包含了报表的加载,并通过ViewBag将其传递给视图。我将报表上传到单独的 SetReport() 方法。
现在考虑Index.cshtml的视图:
@{
ViewBag.Title = "Home Page";
}
@using (Ajax.BeginForm("Update", "Home", new AjaxOptions
{
UpdateTargetId = "UpdateHere"
//HttpMethod = "POST",
//InsertionMode = InsertionMode.Replace,
}))
{
@Html.CheckBox("condition", true)
}
@ViewBag.WebReport.GetHtml()