如何从ajax post call传递多个属性到aspx页面webmethod

How to Pass multiple properties from ajax post call to aspx page webmethod?

本文关键字:属性 aspx webmethod 页面 ajax post call      更新时间:2023-09-26

我使用下面的代码,但我没有得到对象myObj的值。我没有使用MVC。这里我使用了简单的asp.net(c#)。

    类文件
  • public class MyClass
    {
        public string title { get; set; }
        public string songPath { get; set; }
    }
    
  • 。aspx页

    [System.Web.Services.WebMethod]
    public static string PostData(MyClass myObj)
    {            
        // myObj.title should have value = "song title etc...";            
        // myObj.songPath should have value = "song path edc...";            
        return "done";
    }
    
  • JS

    <script type = "text/javascript">
    function PostData() {
        $.ajax({
            type: "POST",
            url: "CreateLeave.aspx/PostData",            
            data: { title: "song title etc...", songPath: "song path edc..." },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("error");
            }
        });
    }
    function OnSuccess(response) {
        alert("success");
    }
    </script>
    

请让我知道我错过了什么。请给我一些建议。由于

如果你在webMethod中使用多个参数,然后在那个方法中创建你的对象呢?

[System.Web.Services.WebMethod]
public static string PostData(string title, string songPath, //...etc)
{   
    MyClass myObj = new myClass();
    myObj.title = title;           
    myObj.songPath = songPath;
    return "done";
}

尝试在ajax调用中像这样更改data属性

data: { "myObj": { title: "song title etc...", songPath: "song path edc..." } }