I can not pass an Object by AJAX to a Visual Basic Function

4

I have a big problem with Ajax MVC and Visual Basic: When I create an object in javascript to do a POST in Controller everything is fine by when I receive the Object in the ActionResult, all the attributes are Nulls.

Can someone help me?

Ajax Code:

    // #region Crear o Actualizar un Item
    function CreateUpdate() {
        var checkBanderas = true;
        var MyObject = {};
        var PasswordRepeat = null;
        // Id Name Description NameOrIP Enabled Default
        if ($('#hdUserId').val() == "") { MyObject.Id = 0; } else { MyObject.Id = $('#hdUserId').val(); }

        if ($('#txt_UserName').val() == "") { MyObject.UserName = null; } else { MyObject.UserName = $('#txt_UserName').val(); }
        if ($('#txt_Password').val() == "") { MyObject.Password = null; } else { MyObject.Password = $('#txt_Password').val(); }
        if ($('#txt_PasswordRepeat').val() == "") { PasswordRepeat == null; } else { PasswordRepeat = $('#txt_PasswordRepeat').val(); }
        if ($('#txt_FirstName').val() == "") { MyObject.FirstName = null; } else { MyObject.FirstName = $('#txt_FirstName').val(); }
        if ($('#txt_LastName').val() == "") { MyObject.LastName = null; } else { MyObject.LastName = $('#txt_LastName').val(); }
        if (MyObject.FirstName == null) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Ingresa el Nombre para poder continuar.", false, " $('#dlgCreateUpdate').modal('show'); FocusTextBox('#txt_FirstName');", null);
            return;
        }
        if (MyObject.LastName == null) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Ingresa el Apellido para poder continuar.", false, " $('#dlgCreateUpdate').modal('show'); FocusTextBox('#txt_LastName');", null);
            return;
        }
        if (MyObject.Password == null) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Ingresa la Contraseña para poder continuar.", false, " $('#dlgCreateUpdate').modal('show'); FocusTextBox('#txt_Password');", null);
            return;
        }
        if (PasswordRepeat == null) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Ingresa la Contraseña de Confirmación para poder continuar.", false, " $('#dlgCreateUpdate').modal('show'); FocusTextBox('#txt_PasswordRepeat');", null);
            return;
        }
        if (MyObject.Password != PasswordRepeat) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Las contraseñas no coinciden.", false, " $('#dlgCreateUpdate').modal('show'); CleanPasswords();", null);
            return;
        }
        if (MyObject.UserName == null) {
            $('#dlgCreateUpdate').modal('hide');
            ShowMessageBox("Error de Validación", "Ingresa el Nombre de Usuario para poder continuar.", false, " $('#dlgCreateUpdate').modal('show'); FocusTextBox('#txt_UserName');", null);
            return;
        }
        var data = MyObject;
        console.log("data: " + JSON.stringify(data));
        $.ajax(
                {
                    url: '/Users/CreateUpdate_Users'
                    , type: "POST"
                    , data: JSON.stringify(data)
                    , dataType: "json"
                    , contentType: 'application/json'
                })
                .done(function (result) {
                    if (result.success) {
                        ShowMessageBox("Guardado", "Los datos han sido guardados correctamente.", false, null, null);
                        DoSearch();
                        //oTable.DataTable();
                    }
                    else {
                        ShowMessageBox("Error", "A ocurrido un error al intentar guardar los datos. Contacte al Administrador del Sistema.", false, "$('#dlgCreateUpdate').modal('show');", null);
                    }
                    //HideLoading();
                })
                .fail(function (e) {
                    alert("Error: " + e.status + ": " + e.statusText, + "[" + e.Message + "]");
                    //HideLoading();
                });

        //ShowLoading();
        $('#dlgCreateUpdate').modal('hide');
    }
    // #endregion

Controller Code

    <HttpPost()>
    Function CreateUpdate_Users(MyObject As Entities.ApiUser) As ActionResult
        Dim Success As Boolean = True
        Dim Message As String = String.Empty
        Dim model As UserModels = New UserModels()
        Try
            Using logic As Logic = New Logic()
                Dim ToSave As Entities.ApiUser = New Entities.ApiUser()
                If (MyObject.Id > 0) Then
                    MyObject.Id = Nothing
                End If
                model.Item = logic.Save_Users(MyObject)
            End Using
        Catch ex As Exception
            Success = False
            Message = ex.Message
        End Try
        Dim c As Object = New With {.success = Success, .message = Message}
        Dim r As JsonResult = Json(c, JsonRequestBehavior.AllowGet)
        Return r
    End Function

End Class

Testing Images:

Debug:

    
asked by Maximiliano Cesán 16.03.2018 в 19:47
source

1 answer

1

SOLUTION !!!!!!

To be able to pass an object from ajax webForm to the Function and the Attributes Accept Nullables values.

Class to Use

Public Class Testing
    Property Id As Nullable(Of Integer)
    Property Name As String
End Class

Function to Use

  <System.Web.Services.WebMethod()>
Public Shared Function CreateUpdate(Item As Testing) As Entities.ApiForm
    Dim form As Entities.ApiForm = New Entities.ApiForm()
    Dim flag As Boolean = False
    Return form
End Function

How to run Ajax

IMPORTANT

The Object that we are going to pass "Item" It must be exactly EQUAL the name of the Parameter that the Function expects and the object is passed exactly as it is set here:

data: '{"Item":' + JSON.stringify (Item) + '}',

var Item = { Id: null }

$.ajax({
            type: "POST",
            url: "ApiEnviromentEditForms.aspx/CreateUpdate",
            data: '{"Item":' + JSON.stringify(Item) + '}',
            contentType: "application/json",
            dataType: "json",
            success: function (response)
            {

                }
                HideLoading();
                $('#modalCreateUpdate').modal('hide');
                swal(
                'Guardado!',
                'El Formulario ha sido guardado con exito.',
                'success'
                )
            },
            failure: function(response) {
                alert(response.d);
                HideLoading();
            }
        });

Test

Clarification : The parameter here is pData because it is already Final version.

    
answered by 20.03.2018 / 01:24
source