[转载]jquery ajax/post/get 传参数给 mvc的action
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的更多相关文章
- jquery ajax/post/get 传参数给 mvc的action
jquery ajax/post/get 传参数给 mvc的action1.ActionResult Test1 2.View Test1.aspx3.ajax page4.MetaObjec ...
- ASP.NET 异步Web API + jQuery Ajax 文件上传代码小析
该示例中实际上应用了 jquery ajax(web client) + async web api 双异步. jquery ajax post $.ajax({ type: "POST&q ...
- ajax向php传参数对数据库操作
刚入门php,要求要对多用户进行批量删除(当然实际中是不可能的),在这就以此为例. 大意就是通过对数据库中用户查询,将用户信息显示在页面表格中,在进行多项选择后将所选行参数通过ajax传入后台php文 ...
- JQuery $.ajax(); 异步访问完整参数
$.ajax 完整参数 jquery中的ajax方法参数 url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post ...
- 兼容ie的jquery ajax文件上传
Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify...悲剧 对 ...
- struts2+jquery+ajax实现上传&&校验实例
一直以为ajax不能做上传,直到最近看了一些文章.需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T 代码和相关配置如下 ...
- js数组作为参数用ajax向后台传参数
/*前台往后台传参数时,可以这样写*/ var chessId = "123"; var i=0; var data = []; /*添加单个参数*/ data.push({nam ...
- jquery.ajax中的ifModified参数的误解
原来以为ifModified是为了在AJAX请求是发送 If-Modified-Since头,让服务端返回304. 测试代码如下: $(function () { test(); window.set ...
- [转载]Jquery Form插件表单参数
表单插件API提供了几个方法,让你轻松管理表单数据和进行表单提交. ajaxForm增 加所有需要的事件监听器,为AJAX提交表单做好准备.ajaxForm不能提交表单.在document的ready ...
随机推荐
- Redis 命令 - Server
BGREWRITEAOF Asynchronously rewrite the append-only file BGSAVE Asynchronously save the dataset to d ...
- Android之帧动画2
创建自定义对话框: // 对话框构建器 Builder builder = new AlertDialog.Builder(this); // 创建出一个空的对话框 final AlertDialog ...
- 文件流操作(FileStream,StreamReader,StreamWriter)
大文件拷贝: /// <summary> /// 大文件拷贝 /// </summary> /// <param name="sSource"> ...
- ASSERT报错:error C2664: “AfxAssertFailedLine”: 不能将参数 1 从“TCHAR []”转换为“LPCSTR”
转载请注明来源:崨雁嫀筝 http://www.cnblogs.com/xuesongshu 这个错误是我在把tinyxml修改为宽字符(Unicode)版本时候遇到的问题,我首先按关键字把所有有ch ...
- 配置tomcat免安装版服务器
一.首先,确保服务器已经安装java环境,没有tomcat的可以到这里下载 http://tomcat.apache.org/ 二.解压下载的压缩包,我是解压到D盘根目录下的.记住这个目录,后面会用到 ...
- Sublime Text 3下 Emmet 使用小技巧
Emmet常用技巧:(输入下面简写,按Tab键可触发效果) 生成 HTML 文档初始结构 html:5 或者 ! 生成 HTML5 结构 ...
- ICallbackEventHandler 接口实现回调处理功能
在最近的项目实现中遇到了一个问题 在数据处理的过程中,需要请求获取数据,再做处理之后,可以在页面及时获取数据 开始时,首先想到的到是写Ajax请求,但在做后续数据处理后,处理获取数据等操作,感觉实现起 ...
- 九度OJ 1541 二叉树【数据结构】
题目地址:http://ac.jobdu.com/problem.php?pid=1541 题目描述: 旋转是二叉树的基本操作,我们可以对任意一个存在父亲节点的子节点进行旋转,包括如下几种形式(设被旋 ...
- 结构型模式——Adapter
1.意图 将一个类的接口转换成客户希望的另一个接口.使得原本由于接口不兼容而不能一起工作的那些类可以一起工作. 2.结构 类适配器 对象适配器 3.参与者 Target定义Client使用的与特定领域 ...
- HTML5之 WebWorkers
为了进行后台计算提供的完全隔离计算方式 不可访问 DOM APIs 不可访问 window object 不可访问 document object 强隔离保证并行计算结果无误(无锁机制) ---- 启 ...