【问题标题】:Send and process an unknown number of parameters to an ASP.NET WebMethod with jQuery使用 jQuery 向 ASP.NET WebMethod 发送和处理未知数量的参数
【发布时间】:2012-09-08 00:16:54
【问题描述】:

我正在构建一个投票应用程序。用户输入一个问题,然后单击一个按钮为答案动态创建文本框。

然后我使用以下代码序列化表单:

var formData = $("#form1").find("input,textarea,select,hidden").not("#__VIEWSTATE,#__EVENTVALIDATION").serializeObject();

我使用 jQuery.ajax 将序列化信息发送到使用 data: formData 的 WebMethod

这是我的问题开始的地方。如果它是静态表单,我的 webmethod 将是;

<WebMethod()>_
Public Shared Function addPoll(byval question as string, byval answer1 as string, etc...)

由于它们是动态的,我如何定义我的参数以及如何在 webmethod 函数中循环它们?

任何帮助将不胜感激......

【问题讨论】:

  • 你可以使用Dictionary 对象吗?它们很容易序列化/反序列化。
  • 你能举个例子吗?以前没用过..
  • 我在下面举了一个例子。希望对您有所帮助。

标签: jquery asp.net webmethod


【解决方案1】:

根据请求,使用通用列表作为参数传递数据的示例(如果我的 VB.NET 语法不符合要求,请原谅我,我多年来一直专注于 C#)

首先,你要定义一个对象:

Public Class QA
    Public Property Question() As String
        Get
            Return m_Question
        End Get
        Set
            m_Question = Value
        End Set
    End Property
    Private m_Question As String
    Public Property Answer() As String
        Get
            Return m_Answer
        End Get
        Set
            m_Answer = Value
        End Set
    End Property
    Private m_Answer As String
End Class

然后定义你的网络方法:

<WebMethod> _
Protected Sub addPoll(args As IEnumerable(Of QA))
    For Each qaPair As QA In args
        'do stuff with qaPair
    Next
End Sub

jQuery 需要将此对象作为表示对象数组的 JSON 字符串传递到后端,如下所示:

[
    { Question: "what is the answer to life, the universe, and everything?",
        Answer: "42" },
    { Question: "what is the average velocity of a laden swallow?",
        Answer: "African or European?" }
]

可以使用JavaScriptSerializer 将其解析为 QA 对象列表。

希望这可以为您解决问题?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多