jquery ajax/post/get 传参数给 mvc的action
1.ActionResult Test1   
2.View  Test1.aspx
3.ajax page
4.MetaObjectMigration.cs     string json convert to class
5.相关的代码下载(包含用的相关类, jquery.json.js等)

ActionResult Test1

public ActionResult Test1(string nameJS, UserInfoInputData model, string js)
        {
            UserInfoInputData userinfo = new UserInfoInputData();
            if (!string.IsNullOrEmpty(js))
            {
                userinfo = (UserInfoInputData)js.ToInputDataObject(typeof(UserInfoInputData));
            }
            
            ViewData["Time"] = model.Name + "  :" + userinfo.Name;
            ViewData["Time2"] = model.age;
            ViewData["Message"] = "Test1  :" + nameJS + "  :" + typeof(UserInfoInputData).ToString();

            ViewData["js"] = userinfo.ToJSON();

            return View();
        }

 

Test1.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Test1</title>
</head>
<body>
    <div>
       The current time is: <%= DateTime.Now.ToString("T") %>
       <br/><br/>
        BO:<%=ViewData["Time"] %>
        <br/><br/>
        BO2:<%=ViewData["Time2"] %>
        <br/><br/>
        Message:<%=ViewData["Message"] %>
        <br/><br/>
        <%=ViewData["js"]%>
    </div>
</body>
</html>

 

ajax page   四种写法

function test(parameters) {
                var sjson = '{ "name~!@#$%^&*(){}|:\"<>?/.,\';\\[]v-name": "nvar", "desc": "des" } ';
                var sjs = '{"Name":"jsname", "age":3}';
                //get post 都可以
                $.post("Test1", "nameJS=" + encodeURIComponent(sjson) + "&model.name=modelName&model.age=3" + "&js=" + encodeURIComponent(sjs));

                //model.name model.Name 都可以
                var json = { "nameJS": "~!@#$%^&*(){}|:\"<>?/.,';\\[]v-name",
                    "model.name": "modelname", "model.age": 1,
                    "js":'{"Name":"jsname", "age":3}'
                };
                $.post("Test1", json);

                var param = {};
                param["nameJS"] = "paramjs";
                param["model.Name"] = "someone";
                param["model.age"] = 2;
                param["js"] = '{"Name":"jsname", "age":3, "Tags":"tag1"}';
                //或者param["js"] = JSON.stringify({"Name":"jsname", "age":3, "Tags":"tag1"});
                $.post("Test1", param);
                
                var metaformJsonItem = new Object();
                metaformJsonItem.nameJS = "~!@#$%^&*(){}|:\"<>?/.,';\\[]v-name";
                metaformJsonItem.js = JSON.stringify({
                    //key:value  key注意大小写
                    "Name": "~!@#$%^&*(){}|:\"<>?/.,';\\[]v-jsname",
                    "Tags": JSON.stringify(["tag1", "tag2"]),
                    "age": 3,
                    "Ids": JSON.stringify([1, 2, 3]), //或者'[1, 2, 3]'
                    "Country": 0,
                    "Countries": JSON.stringify([1, 2])
                });
                metaformJsonItem["model.Name"] = "modelname";
                metaformJsonItem["model.age"] = "11";
                
                $.post("Test1", metaformJsonItem);
            }

 

string json convert to object class

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using Newtonsoft.Json;

namespace Demo.Common.Metaform.UI
{
    public static class MetaObjectMigration
    {
        private enum HandlingMethod
        {
            DoNothing,
            SimpleEnum,
            ArrayOfEnum,
            ArrayOfString,
            ListOfEnum,
            ListOfSerializable
        }

        public static InputDataObject ToInputDataObject(this string jsonXml, Type objectType)
        {
            return jsonXml.FromMetaJson(objectType); ;
        }
               
        
        public static InputDataObject FromMetaJson(this string json, Type objectType)
        {
            string jsonString = GetJsonFromMetaJson(json, objectType);

            JsonSerializer serializer = new JsonSerializer();
            serializer.NullValueHandling = NullValueHandling.Ignore;
            serializer.MissingMemberHandling = MissingMemberHandling.Ignore;

            InputDataObject deserialedObject =
                (InputDataObject) serializer.Deserialize(new StringReader(jsonString), objectType);

            return deserialedObject;

        }

        private static string GetJsonFromMetaJson(string json, Type displayObjectType)
        {
            PropertyInfo[] properties = displayObjectType.GetProperties();

            using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
            {
                using (StringWriter sw = new StringWriter())
                {
                    using (JsonTextWriter writer = new JsonTextWriter(sw))
                    {
                        HandlingMethod handlingMethod = HandlingMethod.DoNothing;
                        bool ignoreThisProperty = false;
                        string newKey = string.Empty;
                        int arrayLevel = 0;
                        Type elementType;

                        while (reader.Read())
                        {
                            if (reader.TokenType == JsonToken.PropertyName)
                            {
                                string propertyJsonName = reader.Value.ToString();
                                var propertyName = propertyJsonName;//JsonNameToPropertyName(propertyJsonName);

                                PropertyInfo propertyInfo = properties.FirstOrDefault(c => (c.Name == propertyName));

                                if (propertyInfo != null)
                                {
                                    ignoreThisProperty = false;

                                    var propertyType = propertyInfo.PropertyType;
                                    if (propertyType.IsEnum)
                                    {
                                        handlingMethod = HandlingMethod.SimpleEnum;
                                    }
                                    else if (propertyType.IsGenericType && propertyType.GetGenericArguments()[0].IsEnum)
                                    {
                                        elementType = propertyType.GetGenericArguments()[0];
                                        handlingMethod = HandlingMethod.ListOfEnum;
                                    }
                                    else if (propertyType.IsGenericType &&
                                             propertyType.GetGenericArguments()[0].IsSerializable)
                                    {
                                        elementType = propertyType.GetGenericArguments()[0];
                                        handlingMethod = HandlingMethod.ListOfSerializable;
                                    }
                                    else if (propertyType.IsArray && propertyType.GetElementType().IsEnum)
                                    {
                                        elementType = propertyType.GetElementType();
                                        handlingMethod = HandlingMethod.ArrayOfEnum;
                                    }
                                    else if (propertyType.IsArray)
                                    {//e.g. string[]
                                        elementType = propertyType.GetElementType();
                                        handlingMethod = HandlingMethod.ArrayOfString;
                                    }
                                    else
                                    {
                                        handlingMethod = HandlingMethod.DoNothing;
                                    }
                                }
                                else
                                {
                                    ignoreThisProperty = true;
                                    continue;
                                }
                                newKey = propertyJsonName;//JsonNameToPropertyName(propertyJsonName);
                                writer.WritePropertyName(newKey);
                            }
                            else if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer)
                            {
                                if (ignoreThisProperty)
                                    continue;

                                string value = reader.Value.ToString();
                                if (handlingMethod == HandlingMethod.SimpleEnum)
                                {
                                    int code;
                                    if (int.TryParse(value, out code))
                                    {
                                        writer.WriteValue(code);
                                    }
                                    else
                                    {
                                        var intList = value.ToIntList();
                                        if (intList != null && intList.Count > 0)
                                        {
                                            writer.WriteValue(intList[0]);
                                        }
                                        else
                                        {
                                            writer.WriteNull();
                                        }
                                    }
                                }
                                else if (handlingMethod == HandlingMethod.ListOfEnum ||
                                         handlingMethod == HandlingMethod.ArrayOfEnum ||
                                    handlingMethod==HandlingMethod.ArrayOfString || 
                                         handlingMethod == HandlingMethod.ListOfSerializable)
                                {
                                    CreateJsonArray(writer, handlingMethod, value, arrayLevel);
                                }
                                else
                                {
                                    writer.WriteValue(value);
                                }
                            }
                            else
                            {
                                //Json Clone
                                switch (reader.TokenType)
                                {
                                    case JsonToken.Comment:
                                        writer.WriteComment(reader.Value.ToString());
                                        break;
                                    case JsonToken.EndArray:
                                        writer.WriteEndArray();
                                        arrayLevel--;
                                        break;
                                    case JsonToken.EndConstructor:
                                        writer.WriteEndConstructor();
                                        break;
                                    case JsonToken.EndObject:
                                        writer.WriteEndObject();
                                        break;
                                    case JsonToken.None:
                                        break;
                                    case JsonToken.Null:
                                        writer.WriteNull();
                                        break;
                                    case JsonToken.StartArray:
                                        writer.WriteStartArray();
                                        arrayLevel++;
                                        break;
                                    case JsonToken.StartConstructor:
                                        writer.WriteStartConstructor(reader.Value.ToString());
                                        break;
                                    case JsonToken.StartObject:
                                        writer.WriteStartObject();
                                        break;
                                    case JsonToken.Undefined:
                                        writer.WriteUndefined();
                                        break;
                                    default:
                                        writer.WriteValue(reader.Value);
                                        break;
                                }
                            }
                        }

                        return sw.ToString();
                    }
                }
            }
        }

        private static void CreateJsonArray(JsonTextWriter writer, HandlingMethod handleingMethod, string value, int arrayLevel)
        {
            IList valueList;
            if (handleingMethod == HandlingMethod.ListOfEnum || handleingMethod == HandlingMethod.ArrayOfEnum)
            {
                valueList = value.ToIntList();
            }
            else
            {
                valueList = value.ToStringList();
            }

            if (valueList.Count > 0)
            {
                if (arrayLevel == 0)
                {
                    writer.WriteStartArray();
                }

                foreach (var i in valueList)
                {
                    writer.WriteValue(i);
                }

                if (arrayLevel == 0)
                {
                    writer.WriteEndArray();
                }
            }
            else
            {
                if (arrayLevel == 0)
                {
                    writer.WriteStartArray();
                    writer.WriteEndArray();
                }
            }
        }

    }

}

 

相关代码下载

 

 

posted on 2013-08-10 20:15  dfg727  阅读(3925)  评论(0编辑  收藏  举报