Home > OS >  Insert data into database using jQuery AJAX in ASP.NET 6.0 MVC Application
Insert data into database using jQuery AJAX in ASP.NET 6.0 MVC Application

Time:09-17

I made the user input part of my project as a modal (pop-up), so I need to transfer the data to the back side (controller) without refreshing the page. For this reason, I chose to use ajax, but I have a problem.

Here my Register Controller.

[HttpPost]
    public JsonResult Register(RegisterViewModel formData)
    {
        var user = new UserRegisterDto
        {
            FirstName = formData.FirstName,
            LastName = formData.LastName,
            Email = formData.Email,
            Password = formData.Password,
            PhoneNumber = formData.PhoneNumber,
            UserType = Data.Enums.UserTypeEnum.user
        };

        var response = _userService.AddUser(user);
        return new JsonResult("Data is Saved");
    }

Here my ajax code

$('#btnRegister').click(function() { debugger
        var user = {
            FirstName:  $('#inputUserFirstName').val(),
            LastName: $('#inputUserLastName').val(),
            Email: $('#inputUserEmail').val(),
            Password: $('#inputUserPassword').val(),
            PasswordConfirm: $('#inputUserPasswordConfirm').val(),
            PhoneNumber: $('#inputUserPhoneNumber').val()
        };

        $.ajax({
            type: 'Post',
            url: '/Auth/Register',
            data: JSON.stringify(user),
            contentType:'application/json; charset=utf-8;',
            dataType: 'json',
            success: function() {       
                alert("saved");
            },
            error: function() {
                alert("no saved");
            }
        });

When I debugged, I saw that the formData parameter in the controller was not getting any data.

I couldn't find where I made the mistake.

CodePudding user response:

You will need to JSON.stringify() your data to transfer it in the request.

Your request should look like this:

$.ajax({
        type: 'Post',
        url: '/Auth/Register',
        data: JSON.stringify(user),
        contentType:'application/json; charset=utf-8;',
        dataType: 'json',
        success: function() {       
            alert("saved");
        },
        error: function() {
            alert("no saved");
        }
    });

For the controller i would do it likes this:

[Route("Auth/Register")]
[HttpPost]
    public IActionResult Register([FromBody] RegisterViewModel formData)
    {
        var user = new UserRegisterDto
        {
            FirstName = formData.FirstName,
            LastName = formData.LastName,
            Email = formData.Email,
            Password = formData.Password,
            PhoneNumber = formData.PhoneNumber,
            UserType = Data.Enums.UserTypeEnum.user
        };

        var response = _userService.AddUser(user);
        return Json(new { @Success = true});
    }
  • Related