MVC—實現ajax+mvc非同步擷取資料

來源:互聯網
上載者:User

標籤:返回   技術分享   test   tar   lin   table   設計   javascrip   前台   

    之前寫過ajax和一般處理常式的結合實現前背景資料交換的部落格,如今做系統用到了MVC,同一時候也用到了非同步擷取資料。

ajax+一般處理常式與MVC+ajax原理是一樣的在"URL"中前者寫的一般處理常式的名字。而後者寫到Controller中須要調用的方法。


Controller中的設計


using System.Collections.Generic;using System.Web.Mvc;namespace mvcAjaxByAjax.Controllers{    //考試試題    public class ExamEntity    {        public int Id { get; set; }        public string ExamName { get; set; }    }    public class mvcAjaxByAjaxController : Controller    {        [HandleError]        public ActionResult Index()        {            return View();        }        /// <summary>        /// 擷取考試資料        /// </summary>        /// <returns></returns>        [HttpPost]        public ActionResult GetExam()        {            //加入employee資料            List<ExamEntity> examList = new List<ExamEntity>()            {                new ExamEntity {Id = 1, ExamName = "語文考試"},                new ExamEntity {Id = 2, ExamName = "數學考試"}            };            //直接返回此類型JSON類型            return Json(examList);        }    }}

View中的設計


@{    ViewBag.Title = "Index";}<script src="~/Scripts/jquery-2.1.3.min.js"></script><h2>ajax擷取資料</h2><script type="text/javascript" language="javascript">    $(function () {        //注冊單擊事件            $("#btTest").click(function() {                $.ajax({                    type: "POST",                    contentType: "application/json",                    url: "GetExam",                    data: "{}",                    dataType: 'json',                    success: function (result) {                        //將返回資料加入到頁面表格中                        $("#tdId1").html(result[0].Id);                        $("#tdName1").html(result[0].ExamName);                        $("#tdId2").html(result[1].Id);                        $("#tdName2").html(result[1].ExamName);                    }                });            });        });        </script><table>    <tr>        <th>考試ID</th>        <th>考試名稱</th>    </tr>    <tr>        <td id="tdId1"></td>        <td id="tdId2"></td>    </tr>    <tr>        <td id="tdName1"></td>        <td id="tdName2"></td>    </tr>    <tr>        <td><input type="button" value="查詢" id="btTest" /></td>    </tr></table>


通過firebug 查看返回的資料




頁面顯示效果



總結

    利用mvc+ajax簡單的實現非同步資料的查詢,直接調用背景Controllers方法。後台方法直接返回資料給前台控制項。


MVC—實現ajax+mvc非同步擷取資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.