.Net Core from提交表單優化


如題,.net Core MVC form表單提交和.net Framework MVC的類似
 
在.net framework MV下的異步表達提交:
1 @using (Ajax.BeginForm("Action", "Controller", new { }, new AjaxOptions() { HttpMethod =  "post", OnSuccess = "afterCreate" }))
2 {
3 }

1.在 .net Core中form 增加了提交的回調事件 ,使用前需要引用<script src="~/lib/jquery/dist/jquery.unobtrusive-ajax.min.js"></script>

1 <form asp-controller="Account" asp-action="SysLogin" method="post" data-ajax="true"   data-ajax-success="afterSuccess">
2 </form>

完整示例:

前台頁面:

 1 @model NetCoreFrame.Entity.FrameEntity.Frame_Codes
 2 <form asp-action="Create" class="layui-form layui-form-pane"  data-ajax-success="afterSuccess" data-ajax="true" data-ajax-method="POST">
 3     <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 4     <div class="layui-form-item">
 5         <label asp-for="CodeName" class="layui-form-label"></label>
 6         <div class="layui-input-block">
 7             <input asp-for="CodeName" type="text" name="CodeName" required  lay-verify="required"
 8                    placeholder="請輸入數據字典名稱" autocomplete="off"  class="layui-input">
 9             <span asp-validation-for="CodeName" class="text-danger"></span>
10         </div>
11     </div>
12     <div class="layui-form-item">
13         <div class="layui-input-block">
14             <button class="layui-btn" lay-submit lay-filter="formSubmit" type="submit">立即提交</button>
15             <button type="reset" class="layui-btn layui-btn-primary">重置</button>
16         </div>
17     </div>
18 </form>

后台頁面:

1 [HttpPost]
2 public string Create(Frame_Codes model)
3 {
4    PageResponse resp = new PageResponse();
5    _service.Add(model);
6    return JsonHelper.Instance.Serialize(resp);
7 }

 

2.但隨着表單控件的豐富,多選,單選等取值會存在問題,因此欠缺很多靈活性,通過form序列化提交進行優化

 1 function serializeObject(form)
 2 {
 3            var o = {};
 4            var a = $(form).serializeArray();
 5            $.each(a, function() {
 6                if (o[this.name]) {
 7                    if (!o[this.name].push) {
 8                        o[this.name] = [o[this.name]];
 9                    }
10                    o[this.name].push(this.value || '');
11                } else {
12                    o[this.name] = this.value || '';
13                }
14            });
15            return o;
16 };
 
3.但在表單序列化中,會自動提交一些不必要的參數,所以通過對form表單控件的取值生成實體對象來進一步優化
如下,在“getFormData”方法中,根據元素標簽遍歷,判斷標簽的類型,重新返回數據resdata
 
 1 <script type="text/javascript">
 2         (function ($) {
 3             $.myPlugin = {
 4                 //初始化
 5                 init: function () {
 6                     $('body').on('click', '#btn_cloas', function () {
 7                         $.myPlugin.closeWin();
 8                     });
 9                 },
10                 //關閉當前窗口
11                 closeWin: function () {  },
12  getFormData: function () {
13                     
14                     var resdata = {};
15                      $('.layui-form').find('input,select,textarea').each(function (r) {
16                         
17                         var id = $(this).attr('id');
18                         var name = $(this).attr('name');
19                         if (!!id||!!name) {
20                             var type = $(this).attr('type');
21                             switch (type) {
22                                 case "radio":
23                                   
24                                     var value = $(this).attr('value');
25                                     if ($("input[name='" + name + "'][value='" + value +  "']").is(":checked"))
26                                     {
27                                         //resdata[name] = value;
28                                         eval("resdata."+name+"='"+value+"'")
29                                     }
30                                     break;
31                                 case "checkbox":
32                                     if ($("#" + id).is(":checked")) {
33                                         resdata[id] = 1;
34                                     } else {
35                                         resdata[id] = 0;
36                                     }
37                                     break;
38                                
39                                 default:
40                                     if ($("#" + id).hasClass('currentInfo')) {
41                                         var value = $("#" + id)[0].lrvalue;
42                                         resdata[id] = $.trim(value);
43                                     }
44                                     else if ($(this).hasClass('edui-default')) {
45                                         if ($(this)[0].ue) {
46                                             resdata[id] = $(this)[0].ue.getContent(null,  null, true);
47                                         }
48                                     }
49                                     else {
50                                         //text
51                                         var value = $("#" + id).val();
52                                         if (id != undefined) {
53                                            // resdata[id] = $.trim(value);
54                                              eval("resdata."+id+"='"+ $.trim(value)+"'")
55                                         }
56                                        
57                                     }
58                                     break;
59                             }
60                            
61                            
62                         }
63                     });
64                     debugger;
65                     return resdata;
66                 }
67             }
68         }(jQuery));
69         $(function () {
70             $.myPlugin.init();
71         })
72     </script>

4.最后ajax提交,注"traditional"要設為“true”,表示按form提交的方式傳值

jquery1.4版本以后,traditional參數,默認false的時候如果是{a:{b:'value'}}是處理成a[b],這樣形式,如果是數組:data:{a:[1,2]},是解析成a[]=1&a[]=2,這種方式后台確實要做兼容(取a[b]或a[])來取值。

完整示例如下:

 1  $('body').on('click', '#btn_finish', function () {
 2             var TableInfo = $.myPlugin.getFormData();
 3             $.ajax({
 4                 url: '/FrameCharts/Create',
 5                 type: "POST",
 6                 data: TableInfo,
 7                 dataType: "json",
 8                 traditional: true,
 9                 success: function (data)
10                 {
11                    if (data.Code == 200)
12                     {
13                         $.myPlugin.closeWin();
14                     }
15                   
16                 }
17             });
18  });

以上,僅學習總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM