ASP.NET MVC中的AJAX

标签: asp.net  ajax  mvc

实体类

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>

运行结果如图:

这里写图片描述

版权声明:本文为WuLex原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/WuLex/article/details/79008510