前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在ASP.MVC中使用Ajax

在ASP.MVC中使用Ajax

作者头像
用户1055830
发布2018-01-18 15:15:58
1.5K0
发布2018-01-18 15:15:58
举报
文章被收录于专栏:飞扬的花生飞扬的花生

      Asp.net MVC 抛弃了Asp.net WebForm那种高度封装的控件,让我们跟底层的HTML有了更多的亲近。可以更自由、更灵活的去控制HTML的结构、样式和行为。Asp.net MVC可以更便捷的使用Ajax,本文针对开发过程中的技术进行了简单的总结并制作了一个小练习进行巩固。

1.准备工作

使用VS创建MVC应用程序,可以使用空模板,添加Home控制器以及对应的视图

使用NuGet进行包管理,添加Jquert、easyui等引用

2.开始制作Demo

UI:

html和JS代码如下:

代码语言:javascript
复制
  1 @{
  2     ViewBag.Title = "Index";
  3 }
  4 
  5 <html>
  6 <head>
  7     <title>
  8     </title>
  9     <script src="~/Script/jquery.min.js"></script>
 10     <link href="~/Script/jquery-easyui-1.4.3/themes/default/easyui.css" rel="stylesheet" />
 11     <script src="~/Script/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
 12     <script src="~/Script/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>
 13     <script>
 14         $(function () {
 15             //使用$.ajax请求
 16             $("#btn").click(function () {
 17                 var getText = $("#txt").val();
 18                 $.ajax({
 19                     url: 'GetGradeByName',
 20                     type: 'post',
 21                     data: { "name": getText },
 22                     success: function (data) {
 23                         if (data) {
 24                             alert(MSG(data))
 25                         }
 26                         else {
 27                             alert("没找到")
 28                         }
 29                     }
 30                 })
 31             })
 32 
 33             //使用$.post请求
 34             $("#btn2").click(function () {
 35                 var getText = $("#txt").val();
 36                 $.post("/Home/GetGradeByName", { "name": getText }, function (data) {
 37                     if (data) {
 38                         alert(MSG(data))
 39                     }
 40                     else {
 41                         alert("没找到")
 42                     }
 43                 })
 44             })
 45 
 46             //使用$.get请求
 47             $("#btn1").click(function () {
 48                 var getText = $("#txt").val();
 49                 $.get("/Home/GetGradeByName?name=" + getText, function (data) {
 50                     if (data) {
 51                         alert(MSG(data))
 52                     }
 53                     else {
 54                         alert("当前学生不存在")
 55                     }
 56                 })
 57             })
 58 
 59             $("#a1").click(function () {
 60 
 61                 $.ajax({
 62                     url: 'JsonObject',
 63                     success: function (data) {
 64                         alert("json字符串是" + data.list);
 65                         var jsonObj = $.parseJSON(data.list);
 66                         alert("长度是" + jsonObj.length);
 67 
 68                         $("#tb").datagrid({
 69                             columns: [[
 70                                   { field: 'stuName', width: 290 },
 71                                 { field: 'stuGrad', width: 290 }
 72                               
 73                             ]],
 74                             pagination: true
 75                         })
 76                         $('#tb').datagrid('loadData', { total: jsonObj.length, rows: jsonObj });
 77 
 78                     }
 79                 })
 80             })
 81 
 82         })
 83         function MSG(s) {
 84             return "恭喜!您的成绩是:" + s;
 85         }
 86     </script>
 87 </head>
 88 <body>
 89     <h1 style=" color:red">ASP.MVC关于Ajax小练习</h1>
 90     @Html.Label("学生姓名:")
 91     @Html.TextBox("txt")
 92     <input id="btn" type="button" value=" $.ajax查询" />
 93     <input id="btn1" type="button" value="$.get查询" />
 94     <input id="btn2" type="button" value="$.post查询" />
 95     <br>
 96     @Html.Label("提示:可以输入 小增、小舒、小郑、小陈", new { style = " color:#ccc" })
 97     <br>
 98     <a id="a1" href="javascript:void(0)">$.ajax返回json字符串</a>
 99     <table id="tb" style="width:50%"></table>
100 </body>
101 </html>

HomeController代码如下:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Ajax.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

        /// <summary>
        /// 说明:根据学生姓名获取成绩
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>      
        public string GetGradeByName(string name)
        {
            StudentGrade studentGrade = new StudentGrade();
            IList<StudentGrade> getList = studentGrade.getAllGrades();
            string s="";
            foreach (StudentGrade model in getList)
            {
                if (model.stuName == name)
                {
                    s = model.stuGrad;
                }
            }
            string sss = s;
            return s;
        }

        /// <summary>
        /// 返回学生列表的Jason字符串
        /// </summary>
        /// <returns></returns>
        public ActionResult JsonObject()
        {
            StudentGrade studentGrade = new StudentGrade();
            IList<StudentGrade> getList = studentGrade.getAllGrades();
            JsonResult jsonResult = new JsonResult();
            jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string st =HttpUtility.HtmlDecode( serializer.Serialize(getList));
            jsonResult.Data = new
            {
                list = st
            };
            return jsonResult;
        }
    }

    /// <summary>
    /// 学生成绩帮助类
    /// </summary>
    public class StudentGrade
    {
        public StudentGrade() { }        
       
        public IList<StudentGrade> getAllGrades()
        {
            IList<StudentGrade> list = new List<StudentGrade>()
           {
               new StudentGrade(){
                 stuGrad="85",
                 stuName="小增"
               },
                  new StudentGrade(){
                 stuGrad="100",
                 stuName="小郑"
               },
               new StudentGrade(){
               stuName="小舒",
               stuGrad="90"
               },
                 new StudentGrade(){
                 stuGrad="60",
                 stuName="小陈"
               }
           };
            return list;

        }
        public string stuName { get; set; }

        public string stuGrad { get; set; }
    }
}

$.ajax的参数简单的说明如下:

http://blog.sina.com.cn/s/blog_4f925fc30100la36.html

3.演示

 (1) 通过实体帮助类构造泛型 学生 对应 成绩列表进行显示(模拟数据库操作)

 (2) 用户可以输入学生姓名进行成绩查询

 (3) 输出查询结果,如果学生不存在则提示

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-10-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档