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

相关代码下载

原文地址:http://www.cnblogs.com/dfg727/archive/2013/08/10/3250548.html

[转载]jquery ajax/post/get 传参数给 mvc的action的更多相关文章

  1. jquery ajax/post/get 传参数给 mvc的action

    jquery ajax/post/get 传参数给 mvc的action1.ActionResult Test1    2.View  Test1.aspx3.ajax page4.MetaObjec ...

  2. ASP.NET 异步Web API + jQuery Ajax 文件上传代码小析

    该示例中实际上应用了 jquery ajax(web client) + async web api 双异步. jquery ajax post $.ajax({ type: "POST&q ...

  3. ajax向php传参数对数据库操作

    刚入门php,要求要对多用户进行批量删除(当然实际中是不可能的),在这就以此为例. 大意就是通过对数据库中用户查询,将用户信息显示在页面表格中,在进行多项选择后将所选行参数通过ajax传入后台php文 ...

  4. JQuery $.ajax(); 异步访问完整参数

    $.ajax 完整参数   jquery中的ajax方法参数 url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post ...

  5. 兼容ie的jquery ajax文件上传

    Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify...悲剧 对 ...

  6. struts2+jquery+ajax实现上传&&校验实例

    一直以为ajax不能做上传,直到最近看了一些文章.需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T 代码和相关配置如下 ...

  7. js数组作为参数用ajax向后台传参数

    /*前台往后台传参数时,可以这样写*/ var chessId = "123"; var i=0; var data = []; /*添加单个参数*/ data.push({nam ...

  8. jquery.ajax中的ifModified参数的误解

    原来以为ifModified是为了在AJAX请求是发送 If-Modified-Since头,让服务端返回304. 测试代码如下: $(function () { test(); window.set ...

  9. [转载]Jquery Form插件表单参数

    表单插件API提供了几个方法,让你轻松管理表单数据和进行表单提交. ajaxForm增 加所有需要的事件监听器,为AJAX提交表单做好准备.ajaxForm不能提交表单.在document的ready ...

随机推荐

  1. Git CMD - clone: Clone a repository into a new directory

    命令格式 git clone [--template=<template_directory>]  [-l] [-s] [--no-hardlinks] [-q] [-n] [--bare ...

  2. Android Studio ndk-Jni开发详细

    http://www.open-open.com/lib/view/open1451917048573.html Java Native Interface (JNI)标准是java平台的一部分,它允 ...

  3. win7 服务详解-系统优化

    Adaptive Brightness监视氛围光传感器,以检测氛围光的变化并调节显示器的亮度.如果此服务停止或被禁用,显示器亮度将不根据照明条件进行调节.该服务的默认运行方式是手动,如果你没有使用触摸 ...

  4. JAVA UDP网络编程学习笔记

    一.UDP网络编程概述 采用TCP协议通信时,客户端的Socket必须先与服务器建立连接,连接建立成功后,服务器端也会持有客户端连接的Socket,客户端的Socket与服务器端的Socket是对应的 ...

  5. Memcached学习(一)

    1.Memcached是什么? 引用维基百科上得简介,Memcached 是一套分布式的高速缓存系统,由LiveJournal的Brad Fitzpatrick开发,目前已被诸如Facebook等许多 ...

  6. 229. Majority Element II My Submissions Question

    Total Accepted: 23103 Total Submissions: 91679 Difficulty: Medium Given an integer array of size n, ...

  7. OC7_目录操作

    // // main.m // OC7_目录操作 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxuemi ...

  8. (转)深入探讨在集群环境中使用 EhCache 缓存系统

    简介: EhCache 是一个纯 Java 的进程内缓存框架,具有快速.精干等特点,是 Hibernate 中默认的 CacheProvider.本文充分的介绍了 EhCache 缓存系统对集群环境的 ...

  9. android 数据库的增删改查

    主java package com.itheima.crud; import android.app.Activity; import android.content.Context; import ...

  10. 串操作,C++实现

    对串的基本操作都全已经实现 对kmp,kf字符串替换等功能全都已经实现 由于时间原因.没来得及注释,希望大家参考见谅. 串操作hstring.h头文件实现 //kallen 1 #ifndef _HS ...