-1

I want to implement a form in which there are various types of inputs, such as several text and file type inputs for sending photo, and the information must be sent through ajax and with a model, and after the operation, the message of the success of the operation with sweet alert will be displayed. The program is written with asp.net core 8. But the action and control are not detected. Model:

public class UserRegisterVM
{
    public Guid? UserId { get; set; }
    public string? UserName { get; set; }
    public int Area {  get; set; }
    public string? Password { get; set; }
    public string? ConfirmPassword {  get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? Gender { get; set; }
    public string? MaritalStatus { get; set; }
    public bool Insurance { get; set; }
    public string? EmploymentStatus {  get; set; }
    public IFormFile? Avatar { get; set; }
    public string? PhoneNumber { get; set; }
    public string? Email { get; set; }
    public string? DateOfBirth { get; set; }
    public string? City { get; set; }
    public string? Address { get; set; }
}

Controller in Province Area and ManagementController and Register Action:

 [HttpPost]
 [ValidateAntiForgeryToken]
 public IActionResult Register(UserRegisterVM user)
 {
     ValidationResult userValidator = _userRegisterValidator.Validate(user);
     bool success = false;
     var message = ".عملیات ثبت با شکست مواجه شده است";
     string checkMessage = "";
     if (userValidator.IsValid)
     {
         try
         {
             bool result = _userService.Register(user, out checkMessage);
             if (result)
             {
                 success = true;
                 message = ".عملیات ثبت کاربر " + user.FirstName + " " + user.LastName + " با موفقیت انجام شد";
             }
             else
             {
                 message = checkMessage;
             }
         }
         catch (Exception ex)
         {
             while (ex.InnerException != null)
             {
                 ex = ex.InnerException;
             }
             message = "خطای شکست عملیات ثبت : " + ex.Message;
         }
     }
     else
     {
         message = ".داده ورودی نمعتبر است";
     }
     #region Manual Validation
     foreach (var error in userValidator.Errors)
     {
         ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
     }
     userValidator.AddToModelState(this.ModelState);
     #endregion

     #region Json data
     var data = new
     {
         success = success,
         message = message,
     };
     #endregion

     return Json(data);
 }

Form in Register View:

<form id="registerForm" enctype="multipart/form-data">
//Text and file type inputs
<button type="submit" class="btn btn-primary" id="submitBtn" >
    ثبت
</button>
</form>

Javascript code to send the model to the action:

$(function () {
    var $file = null;
    var dropZone = $('#uploadAvatarBox');
    $("#submitBtn").off("click");
    $("#submitBtn").on("click", function (e) {
        $.fn.Validation();
        e.preventDefault();
        var $form = $('#registerForm');
        if ($form.valid()) {
            $("#submitBtn").prop('disabled', true);
            var formData = new FormData($form.get(0));
            $.ajax({
                url: '@Url.Action("Register", "Management")',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    if (result.success) {
                        //Grid_Load
                        $("#operation-box").modal("toggle");
                        swal.fire({
                            title: result.message,
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 4000,
                            showClass: {
                                popup: 'animate__animated animate__fadeInDown'
                            },
                            hideClass: {
                                popup: 'animate__animated animate__fadeOutDown'
                            }
                        });
                    } else {
                        swal.fire({
                            title: 'خطا',
                            icon: 'error',
                            text: result.message,
                            showConfirmButton: false,
                            timer: 4000,
                            showClass: {
                                popup: 'animate__animated animate__fadeInDown'
                            },
                            hideClass: {
                                popup: 'animate__animated animate__fadeOutDown'
                            }
                        })
                    }
                },
                complete: function () {
                    $("#submitBtn").prop('disabled', false);
                }
            });
        };
    });

Error Picture: enter image description here

Please help me

3
  • 1
    FormData doesn't encode the data as JSON. You are telling the server you were sending JSON, with contentType: "application/json; charset=utf-8" - but you aren't.
    – CBroe
    Commented Jul 8 at 9:50
  • I set false value for contentType and asp-antiforgery="true" for form tag in view and my problem was solved. Thanks for the advice Commented Jul 8 at 10:32
  • 1
    Let JQuery to handle the contentType. set the contentType:false in your js code Commented Jul 8 at 10:34

0

Browse other questions tagged or ask your own question.