将多个对象从Ajax传递到WebMethod

时间:2016-09-28 12:05:31

标签: jquery ajax vb.net dotnetnuke

我正在将form的信息传递给我的WebMethod。目标是使用表单中的数据填充UseInfo对象,并填充我在NewUser类中添加的一些属性,这些属性也是从ajax请求传递的。

当我作为输入参数UserInfo时,对象在ajax后发布成功。但是,如果我有NewUser对象,则只会填充属性Relationship,但UserInfo对象显示为Nothing。

任何想法我做错了什么?我是否需要为班级NewUser提供不同的结构?

NewUser类

 Public Class NewUser

        Public Property UserInfo As UserInfo
            Get
                Return _UserInfo
            End Get
            Set(value As UserInfo)
                _UserInfo = value
            End Set
        End Property
        Private _UserInfo As UserInfo

        Public Property Relationship As String
            Get
                Return m_Relationship
            End Get
            Set(value As String)
                m_Relationship = value
            End Set
        End Property
        Private m_Relationship As String

    End Class

的WebMethod

    <HttpPost>
<ValidateAntiForgeryToken>
<DnnModuleAuthorize(AccessLevel:=SecurityAccessLevel.View)>
    Public Function AddUserDependant(<FromBody> oNewUser As NewUser) As HttpResponseMessage
        Try
            If Me.UserInfo.IsInRole("Carer") Then
                UsersControllerOmni.CreateDnnUser(oNewUser.UserInfo)

                Return Request.CreateResponse(HttpStatusCode.OK)
            Else
                Return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "")
            End If
        Catch ex As Exception
            Return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)
        End Try

    End Function

AJAX

$.ajax({
      type: "POST",
      cache: false,
      url: serviceUrl + "/ModuleTask/AddUserDependant",
      beforeSend: sf.setModuleHeaders,
      contentType: "application/json; charset=utf-8",
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      data: $("form").serialize()
  }).done(function (result) {


  }).fail(function (xhr, result, status) {
      alert(result);
  });

1 个答案:

答案 0 :(得分:1)

问题是您使用$(“form”)。serialize()将表单字符串发送和编码到WebAPI服务。这会将表单转换为字符串“field1 = value1&amp; field2 = value2&amp; field3 = value3”到WebAPI请求中的对象。所以.NET会尝试将其转换为简单的对象。

为了让您的请求适合您拥有的对象,我建议您更改您的ajax以发送内容类型'json'。

然后添加一个方法来控制表单序列化到客户端对象。

$.ajax({
      type: "POST",
      cache: false,
      url: serviceUrl + "/ModuleTask/AddUserDependant",
      beforeSend: sf.setModuleHeaders,
      contentType: "application/json; charset=utf-8",
      dataType: 'json',
      data: $('form').serializeUserRequest()
}).done(function (result) {
}).fail(function (xhr, result, status) {
      alert(result);
});

注意自定义函数serializeUserRequest(),它生成与服务器端WebAPI参数匹配的json请求对象。

$.fn.serializeUserRequest = function()
{
    var requestObj = { "UserInfo": {}, "Relationship": {} };
    var formData = this.serializeArray();
    $.each(formData , function(i, fd) {
        if (fd.name.indexOf("rel_") == 0) {
          var fld = fd.name.substring(4);
          requestObj.Relationship[fld] = fd.value;
        } else {
          requestObj.UserInfo[fd.name] = fd.value;
        }
    });
    return requestObj;
};

为此,我的假设是你使表单字段名称与UserInfo / Relationship对象属性相同(IE:“DisplayName”,“FirstName”等)。此外,为了在这两个根对象之间拆分表单属性,我将“rel_”添加到映射到Relationship对象的字段,所有其他字段名称将映射到UserInfo。

示例:

<input type="text" name="rel_Name" maxlength="50" size="50"/>