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

泪湿孤枕 提交于 2019-11-27 07:41: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; }
}


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.


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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!