如何通过Ajax JSON将表单数据发送到cs页面的WebMethod ?

时间:2022-11-24 14:31:48

I am trying to send my form data to webmethod through jquery.ajax and json but i am unable to send or get any error in the log. can any one can guide me through this or where am i going wrong?. The .ajax method is not executing and giving and alert as "undefined" ?

我正在尝试通过jquery将我的表单数据发送给webmethod。ajax和json,但是我不能发送或在日志中得到任何错误。有人能指引我走过这段路吗?ajax方法没有执行,并以“未定义”的形式给出警告?

    function Submit() {
    debugger;
    var advantages = [];
    var features = [];
    var Elig_crit = [];
    var Elig_value = [];

    $('#AdvantagesContainer .Advantages').each(function () {

        //var txtAdvantages = $(".Advantages")
        //for (var i = 0; i < txtAdvantages.length; i++) {


        advantages.push($(this).val());

        //}
    });

    $('#FeaturesContainer .Features').each(function () {


        features.push($(this).val());
    });


    $('.Eligibility .EligibilityCrit_TxtBox').each(function () {

        Elig_crit.push($(this).val());

    });


    $('.Eligibility .EligibilityVal_TxtBox').each(function () {

        Elig_value.push($(this).val());
    });

    debugger;
    var objData = { Category: $('#ddlInsCategory option:selected').val(), Company: $("#ddlCompanyName option:selected").val(), PlanName: $("#<%=txtPlanName.ClientID%>").val(), PlanDesc: $("#<%=txtPlanDesc.ClientID%>").val(), features: features, advantages: advantages, Criteria: Elig_crit, Value: Elig_value }
    //var jsonData = JSON.stringyfy({ objData: objData }); 
    debugger;
    $.ajax({
        type: "POST",
        url: "Edit.ascx/Save",
        data: objData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: function (response) {
            alert(response.d);
        }
    });
}

function OnSuccess(response) {
    alert("Success");
}

Currently i havent written any code into my webmethod. I have just made the skeleton to see what data does the json throws.

目前我还没有在webmethod中编写任何代码。我刚做了一个框架,看看json抛出了什么数据。

    [WebMethod]
    public static void Save(object objData)
    {


    }

2 个解决方案

#1


1  

You can create a Strong Type at your server side. This will have proper mappings and its very easy and recommended way to work with jQuery ajax.

您可以在服务器端创建强类型。这将具有正确的映射,以及使用jQuery ajax的非常简单和推荐的方式。

Simply create a custom type at your server side which have property names matching with that of the key in your Javascript object like this (Make sure you have the same name and change the datatype accordingly):-

只需在服务器端创建一个自定义类型,该类型的属性名与Javascript对象中的键名匹配(请确保您具有相同的名称,并相应地更改数据类型):-

public class Foo
{
   public string Category { get; set; }
   public string Company { get; set; }
   public string PlanName { get; set; }
   public string PlanDesc { get; set; }
   public List<string> features{ get; set; }
   public List<string> advantages { get; set; }
   public List<string> Criteria{ get; set; }
   public List<string> Value{ get; set; }
}

Then, change your WebMethod to accept this Type as parameter:-

然后,改变你的WebMethod接受这个类型作为参数:-

[WebMethod]
public static void Save(Foo objData)
{


}

Finally send the JSON data from client:-

最后从客户端发送JSON数据:-

var objData = { Category: $('#ddlInsCategory option:selected').val(), ....
var jsonData = JSON.stringify({ objData: objData }); 

#2


0  

There are several methods how you can achieve this:

有几种方法可以实现这一点:

Because you have tagged WebMethod. You can add a scriptManager to your server-side form which will make all of your WebMethods available in client side.

因为你标记了WebMethod。您可以向服务器端表单中添加scriptManager,它将使所有WebMethods在客户端可用。

using scriptManager

使用scriptManager

  1. Add a script manager to your server-side form
  2. 向服务器端表单添加一个脚本管理器
  3. in case if you are using friendly URLs you need to add the page extension manually. ALSO in your RouteConfig set RedirectMode.Off, if you have redirectMode.permanent your ajax call will fail.

    如果您正在使用友好的url,您需要手动添加页面扩展。在你的RouteConfig中设置RedirectMode。关闭,如果你有重定向模式。永久保存ajax调用将失败。

            if (stringEndsWith(PageMethods.get_path(), "aspx")) {
            } else {
                PageMethods.set_path(PageMethods.get_path() + '.aspx');
            };
    

call your WebMethods directly from your javascript using PageMEthods.

使用PageMEthods直接从javascript调用WebMethods。

PageMethods.FN_TEST(your_parameter, onSucess, onError);
            function onSucess(result) {
                alert(result);

            },
            function onError(result) {
                alert('Something wrong.');
            }

Your page:

你的页面:

using System.Web.Services;
using System.Web.Script.Services;

allow your webpage handle script services by adding ScriptService

允许你的网页通过添加ScriptService来处理脚本服务

[ScriptService]
public partial class your_page : System.Web.UI.Page{

... and your web methods

…和您的web方法

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void FN_TEST(string iParam)
{
    return "You have sent me " + iParam;
    // Your result will be JSONised and look like this {d:Json_object}
    //

}}

**using Ajax post ** assuming your WebMethod is set up as above. your ajax call will look like this:

**使用Ajax post **假设您的WebMethod是如上所述设置的。您的ajax调用将如下所示:

"ajax": {
            "type": "POST",
            "contentType": "application/json",
            "dataFilter": function (data) {
                // as web methods return {d:object} this method gets rid of the extra d container in your result set.
                var msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            "dataType": "json",
            "url": "your_page.aspx/FN_TEST", // your web methode

            "data": function (d) {
                // add your params here,
                return JSON.stringify({ iParam: $("#your_field").val()});
            },
            "success": function (data) {
                // do something with your result

            },


        },

if you want to customize more, you can JSONise all your form-fields, send as string, parse the string back to JSON in your webmethod and process continue your stuffs.

如果您想要定制更多,您可以JSONise所有表单字段,以字符串形式发送,在webmethod中将字符串解析为JSON,并处理您的内容。

Edit above code is not full code, modify as per your need oh btw.. if you are using postback you can retrieve your formfields in the request.form collection. I assume you are not interested in this

编辑以上代码不是完整的代码,根据您的需要进行修改哦,顺便说一下。如果使用回发,可以在请求中检索formfields。形成集合。我猜你对这个不感兴趣。

#1


1  

You can create a Strong Type at your server side. This will have proper mappings and its very easy and recommended way to work with jQuery ajax.

您可以在服务器端创建强类型。这将具有正确的映射,以及使用jQuery ajax的非常简单和推荐的方式。

Simply create a custom type at your server side which have property names matching with that of the key in your Javascript object like this (Make sure you have the same name and change the datatype accordingly):-

只需在服务器端创建一个自定义类型,该类型的属性名与Javascript对象中的键名匹配(请确保您具有相同的名称,并相应地更改数据类型):-

public class Foo
{
   public string Category { get; set; }
   public string Company { get; set; }
   public string PlanName { get; set; }
   public string PlanDesc { get; set; }
   public List<string> features{ get; set; }
   public List<string> advantages { get; set; }
   public List<string> Criteria{ get; set; }
   public List<string> Value{ get; set; }
}

Then, change your WebMethod to accept this Type as parameter:-

然后,改变你的WebMethod接受这个类型作为参数:-

[WebMethod]
public static void Save(Foo objData)
{


}

Finally send the JSON data from client:-

最后从客户端发送JSON数据:-

var objData = { Category: $('#ddlInsCategory option:selected').val(), ....
var jsonData = JSON.stringify({ objData: objData }); 

#2


0  

There are several methods how you can achieve this:

有几种方法可以实现这一点:

Because you have tagged WebMethod. You can add a scriptManager to your server-side form which will make all of your WebMethods available in client side.

因为你标记了WebMethod。您可以向服务器端表单中添加scriptManager,它将使所有WebMethods在客户端可用。

using scriptManager

使用scriptManager

  1. Add a script manager to your server-side form
  2. 向服务器端表单添加一个脚本管理器
  3. in case if you are using friendly URLs you need to add the page extension manually. ALSO in your RouteConfig set RedirectMode.Off, if you have redirectMode.permanent your ajax call will fail.

    如果您正在使用友好的url,您需要手动添加页面扩展。在你的RouteConfig中设置RedirectMode。关闭,如果你有重定向模式。永久保存ajax调用将失败。

            if (stringEndsWith(PageMethods.get_path(), "aspx")) {
            } else {
                PageMethods.set_path(PageMethods.get_path() + '.aspx');
            };
    

call your WebMethods directly from your javascript using PageMEthods.

使用PageMEthods直接从javascript调用WebMethods。

PageMethods.FN_TEST(your_parameter, onSucess, onError);
            function onSucess(result) {
                alert(result);

            },
            function onError(result) {
                alert('Something wrong.');
            }

Your page:

你的页面:

using System.Web.Services;
using System.Web.Script.Services;

allow your webpage handle script services by adding ScriptService

允许你的网页通过添加ScriptService来处理脚本服务

[ScriptService]
public partial class your_page : System.Web.UI.Page{

... and your web methods

…和您的web方法

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void FN_TEST(string iParam)
{
    return "You have sent me " + iParam;
    // Your result will be JSONised and look like this {d:Json_object}
    //

}}

**using Ajax post ** assuming your WebMethod is set up as above. your ajax call will look like this:

**使用Ajax post **假设您的WebMethod是如上所述设置的。您的ajax调用将如下所示:

"ajax": {
            "type": "POST",
            "contentType": "application/json",
            "dataFilter": function (data) {
                // as web methods return {d:object} this method gets rid of the extra d container in your result set.
                var msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            "dataType": "json",
            "url": "your_page.aspx/FN_TEST", // your web methode

            "data": function (d) {
                // add your params here,
                return JSON.stringify({ iParam: $("#your_field").val()});
            },
            "success": function (data) {
                // do something with your result

            },


        },

if you want to customize more, you can JSONise all your form-fields, send as string, parse the string back to JSON in your webmethod and process continue your stuffs.

如果您想要定制更多,您可以JSONise所有表单字段,以字符串形式发送,在webmethod中将字符串解析为JSON,并处理您的内容。

Edit above code is not full code, modify as per your need oh btw.. if you are using postback you can retrieve your formfields in the request.form collection. I assume you are not interested in this

编辑以上代码不是完整的代码,根据您的需要进行修改哦,顺便说一下。如果使用回发,可以在请求中检索formfields。形成集合。我猜你对这个不感兴趣。