zoukankan      html  css  js  c++  java
  • Posting array of JSON objects to MVC3 action method via jQuery ajax

    Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

         var domains = [{
                            DomainName: 'testt1',
                            Price: '19.99',
                            Available: true
                        }, {
                            DomainName: 'testt2',
                            Price: '15.99',
                            Available: false
                        }];
    
                    $.ajax({
                        type: 'POST',
                        url: Url.BasketAddDomain,
                        dataType: "json",
                        data: domains,
                        success: function (basketHtml) {
    
                        },
                        error: function (a, b, c) {
                            alert('A problem ocurred');
                        }
                });

    This is the action method:

    public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
    {
        ...

    Any ideas if it is possible to do this?

    Answers

    You need:

    var domains = { domains: [... your elements ...]};
    
                $.ajax({
                    type: 'post',
                    url: 'Your-URI',
                    data: JSON.stringify(domains),
                    contentType: "application/json; charset=utf-8",
                    traditional: true,
                    success: function (data) {
                        ...
                    }
                });

    In general, check out the Request object in the debugger, you'll see what's being passed and get an idea of how to "speak" HTTP.

    NOTE: Just found this out. The model binder chokes on nullable decimal properties like:

    public decimal? latitude { get; set; }

    So it won't bind that if you're posting to it with a json string that looks like this:

    {"latitude":12.0}

    But it WILL work if you post something like this:

    {"latitude":"12.0"}

    See: http://syper-blogger.blogspot.com/2011/07/hello-world.html

    source:http://stackoverflow.com/questions/6031206/posting-array-of-json-objects-to-mvc3-action-method-via-jquery-ajax

  • 相关阅读:
    web 学习资源整理
    CodeSmith 学习资料收集
    常用 T_SQL 语句
    SQL Server 2000查询分析器自定义查询快捷键
    插入标识列 identity_insert
    c# 上传FTP文件
    (.Net 3.5Sp1)WebForm使用System.Web.Routing
    SPQuery.ViewAttributes
    ChatterBot之linux下安装mongodb 02
    linux端口开放指定端口的两种方法
  • 原文地址:https://www.cnblogs.com/sdream/p/5386953.html
Copyright © 2011-2022 走看看