zoukankan      html  css  js  c++  java
  • ASP.NET MVC 之各种jQuery提交模式实例

    1.$.ajax提交

    var _data = {
        "dictItemID": dictItemID,
        "itemType": itemType,
        "itemName": itemName,
        "itemCode": itemCode
    };
    $.ajax({
        url: "/System/DictItemAdd",
        type: "POST",//此参数在这必须要设置,否则服务端无法获取参数值
        async: false,
        data: _data,
        dataType: "json",
        success: function (data) {
            if (data.result === "error") {
                alert(data.msg);
            }
            else {
                window.location.href = "..\System\DictItemManage";
            }
        },
        error: function () {
        }
    });

    对应的服务的代码

    public JsonResult DictItemAdd()
    {
        //...
        dictItem.ItemType = Convert.ToInt32(Request.Form["itemType"]);
        dictItem.ItemName = Request.Form["itemName"];
        dictItem.ItemCode = Request.Form["itemCode"];
    
        if (string.IsNullOrEmpty(Request.Form["dictItemID"]))
        {
            //...
            return Json(new { result = "", msg = "记录添加失败" });
        }
        else
        {
            //..
            return Json(new { result = "", msg = "记录更新失败" });
        }
    }

     例子2

    第6行:dataType:"json", 用于标识返回的数据格式是json,必须和服务端对应的方法返回值的类型对应.

    第8行:和服务器有对应关系

     1 $.ajax({
     2     url: "/System/GetRoleMenuByRoloID",
     3     type: "POST",
     4     async: false,
     5     data: _data,
     6     dataType: "json",
     7     success: function (data) {
     8         var roleRecords = JSON.parse(data.result);
     9         for (var i = 0; i < roleRecords.length; i++) {
    10             if (roleRecords[i].MenuID != null) {
    11                 $("input[name='" + roleRecords[i].MenuID + "']").attr("checked", true);;
    12             }
    13         }
    14     },
    15     error: function () {
    16        debugger
    17     }
    18 });
    public JsonResult GetRoleMenuByRoloID(string roleID)
    {
        //...
        DataTable dt = bll.GetRoleScope(parms);
        return Json(new { result = JsonConvert.SerializeObject(dt), msg = "" });
    }

    $.ajax单对象提交

    var puzzleObj = GetFormInfo("puzzle");//封装一个JSON对象,它的属性与服务端方法参数对象属性保持一致(大小写)
    puzzleObj.EnablePuzzleName = $("#EnablePuzzle").find("option[value='" + puzzleObj.EnablePuzzle + "']").text();
    puzzleObj.CompanyID = $("#cid").val(); 
    $.ajax({
        processData: false,
        url: "/Company/UpdateCompanyForPuzzle",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(puzzleObj),
        success: function (data) {
            SetFormInfo("show", puzzleObj);
        },
        error: function () {
            debugger
        }
    });
    public string UpdateCompanyForPuzzle(tbiz_CompanyEntity entity)
    {
        tbiz_CompanyBLL companyBLL = new tbiz_CompanyBLL();
        int result = companyBLL.UpdateCompanyPuzzleConfig(entity);
        return JsonConvert.SerializeObject(result);
    }

    //MVC默认会自动提取参数并封装成entity对象

    $.ajax 提交 之processData: false,contentType: "application/json"

    这个方式当服务端方法coding好对应的ViewModel,MVC默认是自动解析好提交参数的,对于这点的原理待学习

    var _menus = [];
    var checkbox = $("#table_module input[type='checkbox']");
    for (var i = 0; i < checkbox.length; i++) {
        if ($(checkbox[i]).is(':checked')) {
            var scopeData = $(checkbox[i]).parent().find("input[type='hidden']").val();
            var menuID = $(checkbox[i]).attr("name");
            var menu = { "MenuID": menuID, "RoleID": roleID, "ScopeData": scopeData };
            _menus.push(menu);
        }
    }
    if (_menus.length > 0) {
        var _menusStr = JSON.stringify(_menus);
        $.ajax({
            processData: false,
            url: "/System/SaveRoleMenuByRoloID",
            type: "POST",
            contentType: "application/json",
            async: false,
            data: _menusStr,//提交前必须序列化
            dataType: "json",
            success: function (data) {
                window.location.href = "..\System\RoleManage";
            },
            error: function () {
                debugger
            }
        });
    }

    服务端

    public JsonResult SaveRoleMenuByRoloID(IList<Menu> records)//定义与JS对应的Menu实体,MVC会自动解析提交参数

    2.$.post

    1).以jQuery的$.post方法提交请求, 并用JSON.parse()方法解析Action方法所返回的由JsonConvert.SerializeObject()方法所序列化的对象字符串结果

    2).注意提交请求参数与接受参数的方式

    function loadDictItem(obj) {
        var id = $(obj).attr("data-dictitemID");
        if(id !=="")
        {
            $.post("..\System\BindDictItemById", { "dictitemID": id }, function (data) {
                var dtResult = JSON.parse(data);
                $("#txtItemName").val(dtResult.ItemName);
                $("#txtItemCode").val(dtResult.ItemCode);
                $("#ItemType").prop("value", dtResult.ItemType);
            });
        }
    }

    //直接返回JSON格式字面值

    public string BindDictItemById(string dictitemID)
    {
        SystemBLL bll = new SystemBLL();
        tcfg_DictItemEntity dictItem = bll.GetDictItemByID(dictitemID);
        return JsonConvert.SerializeObject(dictItem);
    }

    3).$.post()可以直接解析由Action返回的JSON格式数据

    function delDictItem(obj) {
        var id = $(obj).attr("data-dictitemID");
        if (id !== "") {
            $.post("..\System\DelDictItemById", { "dictitemID": id }, function (data) {
                if (data.result === "ok") {
                    $(obj).parent().parent().remove();
                }
            });
        }
    }
    public JsonResult DelDictItemById(string dictitemID)
    {
        SystemBLL bll = new SystemBLL();
        tcfg_DictItemEntity dictItem = bll.GetDictItemByID(dictitemID);
        dictItem.IsDelete = 1;
        string result = bll.UpdateDictItem(dictItem) > 0 ? "ok" :"fail";
        return Json(new { result = result, msg = "" });
    }

     $.ajax 参数API

    async: false,  //async. 默认是 true,即为异步方式
    dataType: "json",
    data: _data,//参数,_data可以是obj结构    
    processData: false,
    contentType: "application/json"    // 1)表示向服务端发送的参数的数据格式必须是json形式字符串,和data参数相关联;
    // 2)不添加 contentType:“application/json“的时候可以向后台发送json对象形式的字符串;
    // 3)当向后台传递复杂json的时候,同样需要添加 contentType:“application/json“,然后将数据转化为字符串;
    // 如果不设置, 在ASP.NET MVC 用action 方法原生对象参数接受请求参数时,无法接收并解析参数

     参考

    提交数组并接接收

    function batchSeach() {
        var staffNameList = $("#staff_name_list").val();
        var staffArray = staffNameList.split("
    ");
        var lengthNum = staffArray.length;
        //staffArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L"];
        var limit = 5;//每页个数
        var pagenum = Math.ceil(staffArray.length / limit);//总页数
        for (var i = 0; i < pagenum; i++) {
            var curpage = i + 1;
            var start = limit * (curpage - 1);
            var perpage = staffArray.slice(start, start + limit);
            $.ajax({
                async: false,
                //processData: false,该方式下,不用设置此参数,否则后台解析不了参数
                type: "POST",
                traditional: true,
                dataType: "json",//返回类型已经是JSON
                url: "/Staff/Batch",
                data: { "names": perpage},
                success: function (data) {
                    bindDataTable(data);
                },
                error: function () {
                   
                }
            });
        }
        return;
    }
    public string Batch(List<string> names)
    {
        for (int i = 0; i < names.Count; i++)
        {
        /* code */
        }
        return JsonConvert.SerializeObject(new { result = true, message = "",data= dataTable });
    }
  • 相关阅读:
    What is OpenOCD?
    OpenOCD Debug Adapter Configuration
    OpenOCD 0.9.0 release
    ARM DEBUGGER FOR NEARLY ONE DOLLAR
    SW-DP (Serial Wire Debug Port) Analyzer plugin for the Saleae Logic
    SWD Connect/Transfer Source Code
    Dapper Miser implementation of CMSIS-DAP, MC HCK as SWD Adapter
    STM32定时器级联 -- AN2592
    Training JTAG Interface
    JTAG Simplified
  • 原文地址:https://www.cnblogs.com/zhuji/p/7814626.html
Copyright © 2011-2022 走看看