star-craft

我是一个实习生 在做项目时用到了一个稍微复杂的表单 因为很多视频教程都是自动装配直接传到后台action

所以遇到不能使用实体类的表单时(我业务的表单列数不固定) 就需要通过JSON.NET来将表单传至后台

1.首先一个是表单 (其实也不用看)(我是新手 所以这个有很多问题 希望有老鸟指导)

 1 <div>
 2     <span>这是本表单第 @ViewBag.RowID 件</span><br />
 3     <span></span>
 4     <form id="form1">
 5         @{
 6             string TypeName = "";
 7             List<string> list = new List<string>();
 8             list.Add("首件");
 9             list.Add("末件");
10             SelectList Slist = new SelectList(list);
11             Dictionary<string, int> dic1 = new Dictionary<string, int>();
12             dic1.Add("首件",0);
13             dic1.Add("末件",1);
14             
15             List<string> list2 = new List<string>();
16             list2.Add("通过");
17             list2.Add("不通过");
18             SelectList Slist2 = new SelectList(list2);
19             Dictionary<string, int> dic2 = new Dictionary<string, int>();
20             dic2.Add("通过", 0);
21             dic2.Add("不通过", 1);
22         }
23         <input type="hidden" name="TableID" id="TableID" value="@ViewBag.TableId" />
24         <input type="hidden" name="RowID" id="RowID" value="@ViewBag.RowID" />
25         <table>
26             <tr>
27                 <th>检测值</th>
28                 <th>实际值</th>
29                 <th>检测模具ID</th>
30             </tr>
31             @foreach (QC_Testing qct in Model)
32             {
33                 if (TypeName != qct.TestTypeName)
34                 {
35                     TypeName = qct.TestTypeName;
36                     <tr><td><h3>@qct.TestTypeName</h3></td></tr>
37                 }
38                 <tr>
39                     <td>@qct.TestValueName</td>
40                     <td>@Html.TextBox("ValueID[" + qct.TestValueID + "]")</td>
41                     <td>@qct.TestToolID</td>
42                 </tr>
43             }
44             <tr>
45                 <td>首末件</td>
46                 <td>@Html.DropDownList("FirstOrEnd", Slist, dic1)</td>
47             </tr>
48             <tr>
49                 <td>判定</td>
50                 <td>@Html.DropDownList("Determine", Slist2, dic2)</td>
51             </tr>
52         </table>
53         <input id="button1" type="button" name="提交" value="提交" />
54         <input id="button2" type="button" name="提交" value="提交" />
55     </form>
56 </div>
View Code

2.jquery

$(\'#button2\').click(
            function () {
                var data = $(\'#form1\').serializeArray();
                var json = JSON.stringify(data);
                $("#div2").append(json);
                $.ajax({
                    url: \'test2\',
                    data: { User: json },
                    type: \'post\',
                    dataType: \'json\',
                    success: function (msg) {
                        alert(msg);
                    }
                });
            }
        )

3.action

public ActionResult Test2([ModelBinder(typeof(JsonBinder<serialize>))]List<serialize> User)
        {
            int TableID;
            int RowID;
            int FirstOrEnd;
            int Determine;
            string tmp = "";
            string regexBase = @"ValueID\\[\\d+\\]";
            Regex rgx = new Regex(regexBase);
            Dictionary<int, string> dic = new Dictionary<int, string>();

            foreach (serialize lize in User)
            {
                if (lize.name == "TableID") TableID = Convert.ToInt32(lize.value);
                if (lize.name == "RowID") RowID = Convert.ToInt32(lize.value);
                if (lize.name == "FirstOrEnd")
                    if (lize.value == "首件") FirstOrEnd = 0;
                    else FirstOrEnd = 1;
                if (lize.name == "Determine")
                    if (lize.value == "通过") Determine = 0;
                    else Determine = 1;
                if (rgx.IsMatch(lize.name, 0))
                {
                    tmp = lize.name;
                    tmp.Remove(lize.name.Length - 1);
                    tmp.Remove(7);
                    dic.Add(Convert.ToInt32(tmp), lize.value);
                }
            }
            return Content("");
        }

处理部分就不用看李 我记得Regex应该写错了 

重要的是 [ModelBinder(typeof(ERP.Helpers.SerializeHelper.JsonBinder<serialize>))]List<serialize> User

User 对应JQuery 中的 data: {User:json}

应该也可以继续加 例如data: {User:json,ID:XX} 

serialize 是我定义的一个实体类 

public class serialize
    {
        public string name { get; set; }
        public string value { get; set; }
    }

以及Newtonsoft.Json 这个部分代码是我在博客园查到的

MVC3/4项目开发中遇到的ajax提交Json数据到后台Controller处理(接收参数:多重JSON) - CSDN博客  

http://blog.csdn.net/lanximu/article/details/17284793

非常感谢

引用的话VS2013 可以直接在项目右键 管理nuget.org程序包 输入JSON.NET 就可以了

namespace MvcApplication3.Helper  
{  
    public class JsonBinder<T> : IModelBinder  
    {  
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)  
        {  
            //从请求中获取提交的参数数据   
            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;  
            //提交参数是对象   
            if (json.StartsWith("{") && json.EndsWith("}"))  
            {  
                JObject jsonBody = JObject.Parse(json);  
                JsonSerializer js = new JsonSerializer();  
                object obj = js.Deserialize(jsonBody.CreateReader(), typeof(T));  
                return obj;  
            }  
            //提交参数是数组   
            if (json.StartsWith("[") && json.EndsWith("]"))  
            {  
                IList<T> list = new List<T>();  
                JArray jsonRsp = JArray.Parse(json);  
                if (jsonRsp != null)  
                {  
                    for (int i = 0; i < jsonRsp.Count; i++)  
                    {  
                        JsonSerializer js = new JsonSerializer();  
                        try  
                        {  
                            object obj = js.Deserialize(jsonRsp[i].CreateReader(), typeof(T));  
                            list.Add((T)obj);  
                        }  
                        catch (Exception e)  
                        {  
                            throw e;  
                        }  
                    }  
                }  
                return list;  
            }  
            return null;  
        }  
    }  
}  

这个可以将你丢到action的json字符串转成数组 或是对象

这样就可以顺利将复杂一些的表通过序列化传到后台了

分类:

技术点:

相关文章: