Search code examples
asp.netjsonbackbone.js

How to read value when using model.save() or fetch()?


Man = Backbone.Model.extend({
        url:'/test.aspx',
        initialize: function(){
        },
        defaults: {
            name:'Jim',
            age: '38'
        },
        validate:function(attributes){
            if(attributes.name == '') {
                return "name can't be null";
            }
        }
    });
    var man = new Man;
    man.set({name:'the5fire'});
    man.save();  //the format is json{"name":"the5fire","age":38}

In test.aspx.cs, how can I read this value {"name":"the5fire","age":38} ?

I have tried Request.Form.ToString() but found no data there.

Chrome developer tools shows this json-format data in the "request payload" block.


update:

If I use man.fetch({ data: { Pagesize: '1', PageIndex: '111' } ), then on the server side, I can use Request.Params["PageIndex"]. But how can I get the name? the age?


Solution

  • You can access the raw body of the request via HttpRequest.InputStream and convert it to a string :

    string jsonstring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
    

    You would then deserialize this string to get an object, for example:

    using System.Web.Script.Serialization;
    JavaScriptSerializer jss = new JavaScriptSerializer();
    var d = jss.Deserialize<dynamic>(jsonstring);
    string name = (string)d["name"];