Pass a user defined object to ASP.NET Webmethod from jQuery, using JSON
Asked Answered
P

2

16

I am trying to pass in some simple JSON to an ASP.NET 4.5 Webmethod from jQuery. And it is not working quite the way I want it. It works if I accept the inputs as separate parameters:

[WebMethod]
public static Address GetJSonAddress(string name, string street)

But if I try to take it as an object it does not work, what gets passed in is simply null:

[WebMethod]
public static Address GetJSonAddress(Address newAddress)

I have tried Webmethods, Pagemethods, WCF using DataContractJsonSerializer...nothing. The Address class is decorated appropriately with Datamember/DataContract. The properties are matched including case.

The jQuery, in which I have tried all manner of passing in the data including wrapping it in an Address object...if I do it any other way than what I have the Webmethod is not called and I get error 500:

Save2 = function () {
var address = { prefix: GLOBALS.curr_prefix };

$('input[id^=' + GLOBALS.curr_prefix + '],select[id^=' + GLOBALS.curr_prefix + ']').each(function () {
       address[this.id.substr(4)] = $.trim($(this).val());
})

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/WebServices/Insert",
    data: JSON.stringify(address),
    dataType: "json",
    success: function (data, textStatus) {
        console.log(data, textStatus);
    },
    failure: function (errMsg) {
        MsgDialog(errMsg);
    }
});
}

Eventually I will have to do this with 121 input strings, and really don't want to have a method with 121 parameters. Any help is appreciated.

Politi answered 6/8, 2013 at 11:28 Comment(2)
What happens if you use data: { newAddress: JSON.stringify(address) } ?Chicken
The Webmethod is not called and I get error 500 at the browser. The POST looks ok: {'Address':{"name":"name","street":"street","city":"city","zip":"11111"}}Politi
L
46

I quickly set up this project and I was able to successfully call my web method, please adjust your code accordingly. Make sure your class property names are the same as the ones that you pass through JavaScript.

Webservice

    public static Contact getContact(Contact cnt)
    {
        cnt.name = "Abijeet Patro";
        cnt.phone = "Blah Blah";
        return cnt;
    }

JavaScript/jQuery

    $(document).ready(function () {
        var cnt = {name:'Hello',phone:'Hello'};
        $.ajax({
            type: "POST",
            url: "/Default.aspx/getContact",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({'cnt':cnt}), // Check this call.
            success: function (data) {
                debugger;
            }
        });
    });

Class

public class Contact
{
    public string name { get; set; }
    public string phone { get; set; }
}

Web Service Called


enter image description here

You can grab the project from here. Also please use fiddler or Chrome to monitor AJAX requests/responses. I've added an image to show how to monitor AJAX requests using Chrome. Fiddler is even better and more detailed.


enter image description here

Lately answered 6/8, 2013 at 11:57 Comment(0)
S
-1

I am not aware of ASP. But in Ruby on Rails we are using the below procedure. My form having nearly 20 fields. Through serializeArray(); I can send all the input field values to controller. Like

Your HTML should be look like

<input class="input" id="violation_date" type="text" name="violation_date" value=""/>

"name" field is mportant here.

var form = $("form#driver_info_form").serializeArray();
var hsh = { }
$.each(form, function(i, e) {
            hsh[e.name] = e.value
        });

var jqxhr = $.post("/app/DriverInfo/save_driver_info", {
            hsh: hsh
        }, function() { });

On controller side we can get param like

{"hsh"=>{"violation_date"=>"date", "violation_time"=>"time", "violation_day"=>"week", "username"=>"name", "address"=>"address", "city"=>"city", "state"=>"state", "zip"=>"", "driver_lic_number"=>"123324", "radio_commercial"=>"Yes", "age"=>"", "birth_date"=>"", "sex"=>"", "hair"=>"", "eyes"=>"", "height"=>"", "weight"=>"", "race"=>""}, "accident_check"=>"false", "misdemeanor"=>"false", "traffic"=>"false", "non_traffic"=>"false", "commercial"=>"Yes"}

From this we can access the values.

I hope this will give some guideline to you.

Stumble answered 6/8, 2013 at 11:46 Comment(1)
What kind of guideline should this give to OP? He asked a specific question to asp.net and you answer how you would do it in a completely different environment.Sherrillsherrington

© 2022 - 2024 — McMap. All rights reserved.