ASP.NET MVC中的AJAX

本文介绍了一个使用ASP.NET的AJAX示例项目,包括实体类、上下文类、控制器及视图的实现方式,并展示了如何通过AJAX进行数据交互,如获取随机目的地列表、展示对象、提交新数据等。

实体类

Destination.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MyAJaxTest.Models
{
    [Table("Destinations")]
    public class Destination
    {
        [Key]
        public string City { get; set; }
        public string Country { get; set; }
        public int Id { get; set; }

        public Destination(string city, string country, int id = 0)
        {
            City = city;
            Country = country;
            Id = id;
        }
        public Destination() { }
    }
}

AjaxContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data;
using System.Data.Entity;

namespace MyAJaxTest.Models
{
    public class AjaxContext : DbContext
    {
        public virtual DbSet<Destination> Destinations { get; set; }
        public AjaxContext()
            : base("DefaultConnection")
        {

        }
    }
}

HomeController.cs

using MyAJaxTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyAJaxTest.Controllers
{
    public class HomeController : Controller
    {
        private AjaxContext db = new AjaxContext();

        public ActionResult RandomDestinationList(int destinationCount)
        {
            var randomDestinationList = db.Destinations.OrderBy(r => Guid.NewGuid()).Take(destinationCount);
            return Json(randomDestinationList, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult HelloAjax()
        {
            return Content("你好!来自控制器!", "text/plain");
        }

        public ActionResult Sum(int firstNumber, int secondNumber)
        {
            return Content((firstNumber + secondNumber).ToString(), "text/plain");
        }

        public ActionResult DisplayObject()
        {
            Destination destination = new Destination("东京", "日本", 1);
            return Json(destination, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DisplayViewWithAjax()
        {
            return View();
        }
        [HttpPost]
        public ActionResult NewDestination(string newCity, string newCountry)
        {
            Destination newDestination = new Destination(newCity, newCountry);
            db.Destinations.Add(newDestination);
            db.SaveChanges();
            return Json(newDestination, JsonRequestBehavior.AllowGet);
        }
    }
}

Index.cshtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AJAX Demo</title>

    <script src="~/Scripts/jquery-1.8.2.js"></script> 
    <script type="text/javascript">
    $(document).ready(function () {
        $('.hello-ajax').click(function () {
            $.ajax({
                type: 'GET',
                url: '@Url.Action("HelloAjax")',
                success: function (result) {
                    $('#result1').html(result);
                }
            });
        });
        $('.sum').click(function () {
            $.ajax({
                type: 'GET',
                data: { firstNumber: 1, secondNumber: 2 },
                url: '@Url.Action("Sum")',
                success: function (result) {
                    $('#result2').html(result);
                }
            });
        });
        $('.display-object').click(function () {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                url: '@Url.Action("DisplayObject")',
                success: function (result) {
                    var resultString = 'Id: ' + result.Id + '<br>City: ' + result.City + '<br>Country: ' + result.Country;
                    $('#result3').html(resultString);
                }
            });
        });
        $('.display-view').click(function () {
            $.ajax({
                type: 'GET',
                dataType: 'html',
                url: '@Url.Action("DisplayViewWithAjax")',
                success: function (result) {
                    $('#result4').html(result);
                }
            });
        });

        $('.display-random-database-items').submit(function (event) {
            event.preventDefault();
            console.log($(this).serialize());
            $.ajax({
                url: '@Url.Action("RandomDestinationList")',
                type: 'GET',
                data: $(this).serialize(),
                dataType: 'json',
                success: function (result) {
                    var stringResult = '<ul>';
                    for (var i = 0; i < result.length; i++) {
                        stringResult += '<li>' + result[i].City + ', ' + result[i].Country + '</li>';
                    }
                    stringResult += '</ul>';
                    $('#result5').html(stringResult);
                }
            });
        });
        $('.new-destination').submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: '@Url.Action("NewDestination")',
                type: 'POST',
                dataType: 'json',
                data: $(this).serialize(),
                success: function (result) {
                    var resultMessage = 'You\'ve added a new destination to the database!<br>Id: ' + result.Id + '<br>City: ' + result.City + '<br>Country: ' + result.Country;
                    $('#result6').html(resultMessage);
                }
            });
        });
    });
    </script>
</head>
<body>
    <h2>基础 AJAX</h2>
    <h4 class="hello-ajax">Hello AJAX</h4>
    <div id="result1"></div>
    <hr />
    <h2>使用参数</h2>
    <h4 class="sum">Sum</h4>
    <div id="result2"></div>
    <hr />
    <h2>使用JSON来显示一个对象</h2>
    <h4 class="display-object">显示对象</h4>
    <div id="result3"></div>
    <hr />
    <h2>显示一个视图</h2>
    <h4 class="display-view">显示视图</h4>
    <div id="result4"></div>
    <hr/>
    <h2>使用表单进行GET请求</h2>
    <form action="RandomDestinationList" class="display-random-database-items">
        <label for="destinationCount">你想看多少个目的地?</label>
        <input type="number" name="destinationCount" />
        <button type="submit">提交</button>
    </form>
    <div id="result5"></div>
    <h2>用POST请求提交数据</h2>
    <form action="NewDestination" class="new-destination">
        <label for="newCity">城市: </label>
        <input type="text" name="newCity" />
        <label for="newCountry">国家: </label>
        <input type="text" name="newCountry" />
        <button type="submit">提交</button>
    </form>
    <div id="result6"></div>
</body>
</html>

DisplayViewWithAjax.cshtml

<div id="display-view-with-ajax">
    <h2>欢迎使用DisplayViewWithAjax.cshtml</h2>
    <h4> 我们只是使用AJAX来显示一个视图!</h4>
</div>

运行结果如图:

这里写图片描述

支持 MS SQL 2005 之前的版本 不支持 sql 2008介绍Log Explorer主要用于对MSSQLServer的事物分析和数据恢复。你可以浏览日志、导出数据、恢复被修改或者删除的数据(包括执行过update,delete,drop和truncate语句的表格)。一旦由于系统故障或者人为因素导致数据丢失,它能够提供在线快速的数据恢复,最大程度上保证恢复期间的其他事物不间断执行。他可以支持SQLServer7.0、SQLServer2000和SQLServer2005,提取标准数据库的日志文件或者备份文件中的信息。其中提供两个强大的工具:日志分析浏览,对象恢复。具体功能如下:l 日志文件浏览l 数据库变更审查l 计划和授权变更审查l 将日志记录导出到文件或者数据库表l 实时监控数据库事物l 计算并统计负荷l 通过有选择性的取消或者重做事物来恢复数据l 恢复被截断或者删除表中的数据l 运行SQL脚本产品LogExplore包含两部分l 客户端软件l 服务器代理服务器端代理是保存在SQLServer主机中的一个只读存储过程,他的作用是接受客户端请求,读取在线事物日志块并通过网络传给客户端软件,由客户端软件来读取这些原始的数据块来完成Log Explore所提供的所有功能。他依赖来的网络协议包括:l Named Pipe:局域网中适用l Tcp/Ip:广域网中适用数据库相关介绍事物日志(Transaction Log)SQLServer的每个数据库都包含事物日志,它以文件的形式存储,可以记录数据库的任何变化。发生故障时SQLServer就是通过它来保证数据的完整性。操作(Operation)操作是数据库中定义的"原子行为",每个操作都在日志文件中保存为一条记录。它可以是用户直接输入的SQL语句,比如标准的insert命令,日志文件中便会记录一条操作代码来标志这个insert操作。事物(Transaction)事物是一系列操作组成的序列。他可以理解为直观的不可分割的一笔业务,可以执行成功或者失败。典型的事物比如由应用程序发出的具有开启-提交功能的一组SQL语句。不同的事物靠事物Id号(transaction ID)来区分,具有相同ID的事物记录的日志也相同。在线事物日志(Online Transaction Log)在线事物日志是指当前活动数据库所用的日志。可以通过如下命令来确定其对应文件Select * from SYSFILES他的文件后缀名一般是.LDF离线事物日志(Offline Transaction Log)离线事物日志是指非活动数据库所用的日志。当其数据库处于关闭(ShutDown)才状态下可以进行复制备份操作。他的结果同在线事物日志完全相同。备份文件备份文件是保存食物日志备份的文件,通常管理员通过运行SQL语句或者企业管理器来生成该文件。备份文件的内部结构和事物日志不同,他采用称为MTF的格式来保存数据。一个备份文件可以包含一个日志的多组备份,甚至包括多个数据库的混合备份.设置为自动收缩企业管理器--服务器--右键数据库--属性--选项--选择"自动收缩"强烈要求该项不要选中.否则SQLServer将已循环的方式来覆盖先前的日志记录,将会导致LogExplore无法恢复错误.数据恢复介绍LogExplore允许你恢复应为误操作或者程序错误而导致的数据丢失或者更改.比如执行update\Delete语句时丢失了where子句,或者错误使用了Dts功能.LogExplore不支持直接修改数据库.他可以生成事物的逆操作脚本.如果log是delete table where ...的话,生成的文件代码就是insert table ....你可以通过SQL查询分析器,或者LogExplore的Run SQL Script功能来执行生成脚本.关于UndoUndo功能可以逆操作一组指定的用户事物。包括insert,delete和update,其局限性如下:l 事物类别:LogExplore只能undo用户事物。用户事物是指在用户表上定义的事物,不支持系统表的更新恢复。同时,他也不支持计划变更的回滚。l Blob类型:包括text,ntext,image类型。LogExplore只支持这些类型的insert和delete恢复,不支持update语句恢复。关于redoRedo功能可以再次运行一组指定事物。它可以在以下情况中用到:丢失数据库而且没有任何备份文件。l 如果原始日志文件没有丢失可以通过Redo来实现恢复。l 通过完整备份文件来把数据库恢复到某指定时间点,再通过redo功能完整恢复。它可以重放Create Table和Create Index命令,来重新生成被删掉的表,同时也受blob字段的限制。拯救Dropped/Truncate命令导致的数据丢失执行Drop Table和Truncate Table命令虽然会被SQLServer记录到日志文件中,但是并不记录被删除的数据。你可以使用LogExplore提供的功能来恢复这些数据。LogExplore提供两种机制来恢复被Drop或者Truncate的数据。1、如果你有备份文件可以直接通过备份文件恢复。2、通过LogExplore提供的方法来恢复。当执行如上命令时,SQLServer会将保存数据的页面放入空闲页面列表中。如果此页没有被再次使用则将一直保存原始数据。恢复时,LogExplore将从空闲页面列表中搜寻没有被再次使用的页面,然后生成一个SQL脚本来从这些页面重组原始数据。LogExplore可以确定被删掉的原始数据行,并在完成时显示原始行数和实际恢复的行数,由此可以断定是否全部恢复。SQL逆操作1、Insert--Delete2、Delete--Insert3、Update注意:如果你选中了'Do not restore column values that have been changed by subsequent modifications'项,只对事物1逆转将不会产生任何结果。自增序列(IDENTITY Property)如果被删除数据与有IDENTITY Property属性,恢复时LogExlpore可以通过SET IDENTITY_INSERT ON 命令来对插入的数据设置Identity属性,并保留原数据不变,也可以对该列付与新值。数据导出:浏览日志时可将数据导出为xml,html,或者其他有分隔符的文件.也可以指定到一个SQL的表中.操作指南Attaching to a Log:在所有操作之前必须添加日志文件,l 可以用普通的SQL登录方式添加在线日志(Online Log),l 直接选择LDF文件来添加离线日志(OffLine Log)l 添加备份文件登录之后界功能介绍:1、 Log Summary日志文件的概要信息。2、 Load Analysis列出指定时间范围内的一些事物,用户和表载入的概要信息。3、 Filter Log Record日志过滤设置。支持过滤条件包括:时间、操作类型、表、用户、SPID、搜索深度、Dropped表项以及登录设置和应用程序设置4、Browse日志浏览,核心模块。1、 View Log功能:列表如图,可以用TransID来区分事物并用不同颜色标识。工具栏的按钮是一些基本查询操作。鼠标右键弹出菜单中有Undo Transaction和UndoOperation可以恢复黑色箭头选中的事物或者操作项。Real-Time Monitor:实时监控事物日志,通过轮询来实现。可以暂停或者停止监控,可以更改轮询周期。相关DML语言和DDL语言可以在Row Revision History、Row Transaction History以及View DDL Commands来查询。2、 Export Log Report包括Export To SQL和Export To File,根据向导即可完成。3、 其余菜单:Undo,Redo,Salvage Dropped/Truncated data,Restore 以及Run SQL Script前面已经叙述过,可以根据其向导完成。log explorer使用的几个问题1)对数据库做了完全 差异 和日志备份备份时选用了删除事务日志中不活动的条目再用Log explorer打试图看日志时提示No log recorders found that match the filter,would you like to view unfiltered data选择yes 就看不到刚才的记录了如果不选用了删除事务日志中不活动的条目再用Log explorer打试图看日志时,就能看到原来的日志2)修改了其中一个表中的部分数据,此时用Log explorer看日志,可以作日志恢复3)然后恢复备份,(注意:恢复是断开log explorer与数据库的连接,或连接到其他数据上,否则会出现数据库正在使用无法恢复)恢复完后,再打开log explorer 提示No log recorders found that match the filter,would you like to view unfiltered data选择yes 就看不到刚才在2中修改的日志记录,所以无法做恢复.3)不要用SQL的备份功能备份,搞不好你的日志就破坏了.正确的备份方法是:停止SQL服务,复制数据文件及日志文件进行文件备份.然后启动SQL服务,用log explorer恢复数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值