Jquery Ajax方法向action传递参数深度解析(补充篇)

0 下载量 42 浏览量 更新于2024-08-31 收藏 74KB PDF 举报
"本文主要补充了关于使用Jquery Ajax方法向控制器Action传递数据的细节,包括如何传递单个模型对象和列表模型对象。" 在Web开发中,jQuery的Ajax方法是一个非常常用的功能,用于实现页面与服务器之间的异步数据交互。在ASP.NET MVC框架下,我们经常需要将前端的数据发送到后端的Controller方法进行处理。本文将深入探讨如何使用jQuery Ajax方法向Action传递`PersonModel`单个实例和列表。 首先,我们来看一个简单的`PersonModel`类的定义: ```csharp public class PersonModel { public int id { set; get; } public string name { set; get; } public int age { set; get; } public bool gender { set; get; } public string city { set; get; } public override string ToString() { return string.Format(@"id:{0} name:{1} age:{2} gender:{3} city:{4}", id, name, age, gender, city); } } ``` 这个模型类包含了一个人的基本信息,如ID、姓名、年龄、性别和城市。 接下来,我们有两个Controller中的Action方法来处理这些数据: 1. 接收单个`PersonModel`实例: ```csharp public ActionResult ReadPerson(PersonModel model) { string s = model.ToString(); return Content(s); } ``` 2. 接收`PersonModel`的列表: ```csharp public ActionResult ReadPersons(List<PersonModel> model) { string result = ""; if (model == null) return Content(result); foreach (var s in model) { result += s.ToString(); result += "-------------"; } return Content(result); } ``` 在前端使用jQuery的Ajax方法来发送数据时,对于单个模型对象,可以这样编写JavaScript代码: ```javascript var person = { id: "001", name: "zhangsan", age: "20", gender: true, city: "shanghai" }; var option = { url: '/test/ReadPerson', type: 'POST', data: JSON.stringify(person), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(response) { // 处理返回的数据 }, error: function(xhr, status, error) { // 错误处理 } }; $.ajax(option); ``` 这里我们使用`JSON.stringify()`方法将JavaScript对象转换成JSON字符串,然后通过Ajax的`data`属性传递给服务器。同时,我们需要设置`contentType`为`'application/json; charset=utf-8'`,告诉服务器我们将以JSON格式发送数据。 对于传递列表,可以先将多个`PersonModel`对象组合成一个数组,然后再转换成JSON字符串: ```javascript var persons = [ { id: "001", name: "zhangsan", age: "20", gender: true, city: "shanghai" }, { id: "002", name: "lisi", age: "30", gender: false, city: "beijing" } ]; var option = { url: '/test/ReadPersons', type: 'POST', data: JSON.stringify(persons), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(response) { // 处理返回的数据 }, error: function(xhr, status, error) { // 错误处理 } }; $.ajax(option); ``` 这样,我们就成功地使用jQuery的Ajax方法向服务器的Action传递了单个模型和模型列表。在实际开发中,还需要考虑错误处理、数据验证和安全性等问题,以确保应用程序的稳定性和安全性。