.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  });

以上,仅学习总结

原文地址:https://www.cnblogs.com/ywkcode/p/12878555.html