Student类有集合属性Courses,如何把Student连同集合属性Courses传递给控制器方法?

    public class Student
    {
        public string StudentName { get; set; }
        public IList<Course> Courses { get; set; }
    }

    public class Course
    {
        public string CourseName { get; set; }
    }

□ 思路

在前端拼装成与Student吻合、对应的对象,再使用JSON.stringify()或$.toJSON()方法转换成json格式传递给控制器方法,使用$.toJSON()方法需要引用一个jQuery的扩展js文件。  

□ Home/Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<a id="btn" href="javascript:void(0)">走你</a>
 
@section scripts
{
    <script src="~/Scripts/json.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btn').click(function() {
                var arr = [];
 
                var obj1 = new Object();
                obj1.CourseName = "语文";
                arr.push(obj1);
 
                var obj2 = new Object();
                obj2.CourseName = "数学";
                arr.push(obj2);
 
                var student = {
                    StudentName: '小明',
                    Courses: arr
                };
 
                //var json = JSON.stringify(student);
                var json = $.toJSON(student);
 
                $.ajax({
                    url: '@Url.Action("GetStuent","Home")',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: json,
                    dataType: 'json',
                    success: function (data) {
                        alert(data.StudentName);
                        for (i = 0; i < data.Courses.length; i++) {
                            alert(data.Courses[i].CourseName);
                        }
                    }
                });
            });
            
        });
    </script>
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ HomeController

        public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult GetStuent(Student student)
        {
            return Json(student);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 把对象转换成json格式的jQuery扩展

// From: http://www.overset.com/2008/04/11/mark-gibsons-json-jquery-updated/
 
(function ($) {
    m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
    $.toJSON = function (value, whitelist) {
        var a,          // The array holding the partial texts.
            i,          // The loop counter.
            k,          // The member key.
            l,          // Length.
            r = /["\\\x00-\x1f\x7f-\x9f]/g,
            v;          // The member value.
 
        switch (typeof value) {
            case 'string':
                return r.test(value) ?
                '"' + value.replace(r, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"' :
                '"' + value + '"';
 
            case 'number':
                return isFinite(value) ? String(value) : 'null';
 
            case 'boolean':
            case 'null':
                return String(value);
 
            case 'object':
                if (!value) {
                    return 'null';
                }
                if (typeof value.toJSON === 'function') {
                    return $.toJSON(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length'))) {
                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push($.toJSON(value[i], whitelist) || 'null');
                    }
                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {
                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = $.toJSON(value[k], whitelist);
                            if (v) {
                                a.push($.toJSON(k) + ':' + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (typeof k === 'string') {
                            v = $.toJSON(value[k], whitelist);
                            if (v) {
                                a.push($.toJSON(k) + ':' + v);
                            }
                        }
                    }
                }
                return '{' + a.join(',') + '}';
        }
    };
 
})(jQuery);      

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

使用jQuery异步传递含复杂属性及集合属性的Model到控制器方法的更多相关文章

  1. Struts(二十一):类型转换与复杂属性、集合属性配合使用

    背景: 本章节主要以复杂属性.集合属性类型转化为例,来学习这两种情况下怎么使用. 复杂对象属性转换场景: 1.新建struts_04 web.xml <?xml version="1. ...

  2. 使用jQuery异步传递Model到控制器方法,并异步返回错误信息

    需要通过jquery传递到控制器方法的Model为: public class Person { public string Name { get; set; } public int Age { g ...

  3. XStream别名;元素转属性;去除集合属性(剥皮);忽略不需要元素

    city package xstream; public class City { private String name; private String description; public St ...

  4. 如何利用jQuery post传递含特殊字符的数据【转】

    在jQuery中,我们通常利用$.ajax或$.post进行数据传递处理,但这里通常不能传递特殊字符,如:“<”.本文就介绍如何传递这种含特殊字符的数据. 1.准备页面和控制端代码 页面代码如下 ...

  5. MVC验证11-对复杂类型使用jQuery异步验证

    原文:MVC验证11-对复杂类型使用jQuery异步验证 本篇体验使用"jQuery结合Html.BeginForm()"对复杂类型属性进行异步验证.与本篇相关的"兄弟篇 ...

  6. jQuery异步获取json数据的2种方式

    jQuery异步获取json数据有2种方式,一个是$.getJSON方法,一个是$.ajax方法.本篇体验使用这2种方式异步获取json数据,然后追加到页面. 在根目录下创建data.json文件: ...

  7. Hibernate 集合映射 一对多多对一 inverse属性 + cascade级联属性 多对多 一对一 关系映射

    1 . 集合映射 需求:购物商城,用户有多个地址. // javabean设计 // javabean设计 public class User { private int userId; privat ...

  8. 编写高质量代码改善C#程序的157个建议——建议25:谨慎集合属性的可写操作

    建议25:谨慎集合属性的可写操作 如果类型的属性中有集合属性,那么应该保证属性对象是由类型本身产生的.如果将属性设置为可写,则会增加抛出异常的几率.一般情况下,如果集合属性没有值,则它返回的Count ...

  9. 六 Spring属性注入的四种方式:set方法、构造方法、P名称空间、SPEL表达式

    Spring的属性注入: 构造方法的属性注入 set方法的属性注入

随机推荐

  1. HDU 3613 Best Reward(manacher求前、后缀回文串)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3613 题目大意: 题目大意就是将字符串s分成两部分子串,若子串是回文串则需计算价值,否则价值为0,求分 ...

  2. MySQL学习笔记:生成一个时间序列

    今天遇到一个需求是生成以下表格的数据,一整天24小时,每秒一行数据. 寻找颇旧,找到另外两个实现的例子,暂且学习一翻.另一个见另外一篇. DAY) AS DATE FROM ( ) AS tmp, ( ...

  3. 开源的python机器学习模块

    1. Scikit-learn Scikit-learn 是基于Scipy为机器学习建造的的一个Python模块,他的特色就是多样化的分类,回归和聚类的算法包括支持向量机,逻辑回归,朴素贝叶斯分类器, ...

  4. CentOS6.9 安装OpenResty

    1.安装依赖包 yum install -y gcc gcc-c++ readline-devel pcre-devel openssl-devel tcl perl 2.安装OpenResty 首先 ...

  5. HTML--1

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

  6. Java 中byte 与 char 的相互转换 Java基础 但是很重要

    char转化为byte: public static byte[] charToByte(char c) {        byte[] b = new byte[2];        b[0] = ...

  7. bzoj 1820 dp

    最普通dp要4维,因为肯定有一个在上一个的位置,所以可以变为3维,然后滚动数组优化一下. #include<bits/stdc++.h> #define LL long long #def ...

  8. 006 ajax验证用户名

    1.大纲 2.index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8&qu ...

  9. 理解事件(Event)

    Overview 在前几章,我们已经对委托有了一个完整的了解了,本章将会对事件进行一下介绍: 相对于委托,事件再是我们更加频繁的接触的,比如 鼠标的click 事件,键盘的 keydown 事件等等. ...

  10. 你见过这些JavaScript的陷阱吗?

    一.成员操作符 Number.prototype.testFn=function () { console.log(this<0, this.valueOf()); } var num = -1 ...