zoukankan      html  css  js  c++  java
  • AJAX,JSON与MVC

    有几个特殊之处

    1. MVC框架中包含了一个特殊的JSONActionResult,可以直接返回JSON对象,注意它的格式与之前的asmx和页面静态方法都不一样,它直接就是一个JSON对象

    image

    2. 服务端和客户端编程都相对简单了。服务器端无须明确序列化,而客户端也无须解析JSON字符串了,因为返回的结果本来就是一个JSON对象

    第一部分:Controller中的设计

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcApplication1.Controllers
    {
    
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    
        [HandleError]
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewData["Message"] = "Welcome to ASP.NET MVC!";
    
                return View();
            }
    
            public ActionResult About()
            {
                return View();
            }
    
            public ActionResult Employee() {
                return View();
            }
    
    
            [HttpPost]
            public ActionResult GetEmployee() {
                return Json(new Employee()
                {
                    Id = 1,
                    Name = "chenxizhang"
                });
            }
    
    
            
            
        }
    }
    

    第二部分:View中的设计

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        GetEmployee
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
        <script src="../../Scripts/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
    
        <script type="text/javascript" language="javascript">
            $(function() {
                $("#bt").click(function() {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "http://localhost:44203/Home/GetEmployee",
                        data: "{}",
                        dataType: 'json',
                        success: function(result) {
                            alert(result.Id);
                        }
    
                    });
                });
            });
        
        </script>
    
        <h2>
            GetEmployee</h2>
        <input type="button" value="Invoke" id="bt" />
        <div id="info">
        </div>
    </asp:Content>
    
  • 相关阅读:
    cad是什么意思?教你快速把cad转换成pdf格式
    为什么街上的商贩更喜欢用微信支付,而不是支付宝,看完长知识了
    音乐剪辑软件怎么用?教你一个快速编辑音频的方法
    电脑如何录制视频?安利两种电脑录屏的方法
    被称为逆天改命的5大中国工程,曾轰动世界,你知道几个?
    如何使用音乐格式转换器?快速编辑音频文件的方法
    PPT结尾只会说“谢谢”?学会这些PPT结尾,观众主动为你鼓掌
    经典PHP面试题(冒泡排序),当场就被打脸,卧槽什么冒泡?为啥还排序?
    千万不要再搞混了,函数empty( var );输出的判断值是false : true
    PHP删除数组中空数组
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1660601.html
Copyright © 2011-2022 走看看