Hello! There is a controller:

[HttpPost] [AllowAnonymous] public JsonResult ChangePassword(ChangePasswordModel model, string captcha) { User result; if (string.IsNullOrWhiteSpace(captcha) || GoogleCaptcha.Validate(captcha) != "True") { result = new User { Error = "Проверка безопасности не была пройдена, повторите попытку", Status = 1 }; return Json(JsonConvert.SerializeObject(result)); } if (!ModelState.IsValid) { if (model.OldPassword == null || model.Password == null || model.ConfirmPassword == null) { result = new User { Error = "Все поля являются обязательными", Status = 1 }; return Json(JsonConvert.SerializeObject(result)); } result = new User { Error = "При смене пароля произошла непредвиденная ошибка", Status = 1 }; return Json(JsonConvert.SerializeObject(result)); } ... // тут уже остальная логика } 

script that receives data from the form:

 function ChangePassword() { $('.messageBox').empty(); var formData = $('#ChangePasswordForm').serialize(); var captchaCode = $('#g-recaptcha-response').val(); if ($('#ChangePasswordForm').valid() == true) { $('#change-password-button').attr('disabled', 'disabled'); $.ajax({ type: 'POST', url: '/ChangePassword', data: { formData: formData, captcha: captchaCode }, success: function (data) { var jsonResult = $.parseJSON(data); if (jsonResult.Status == 0) { $('#ChangePasswordForm').css('display', 'none'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="success"><p>Ваш пароль был успешно изменен на новый!</p></div>'); } else { $('#change-password-button').removeAttr('disabled'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="errors">' + jsonResult.Error + '</div>'); } }, error: function (data) { var jsonResult = $.parseJSON(data); $('#change-password-button').removeAttr('disabled'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="errors">' + jsonResult.Error + '</div>'); } }); } } 

View with the form itself:

 <form id="ChangePasswordForm" onsubmit="return false;" novalidate="novalidate"> <table class="tableform" id="change-password-form"> <tbody> <tr> <td class="label">@Html.LabelFor(m => m.OldPassword)</td> <td>@Html.TextBoxFor(m => m.OldPassword, new { @type = "password", @id = "OldPassword", @placeholder = "Введите старый пароль", @maxlength = "30", @size = "25" })</td> </tr> <tr> <td class="label">@Html.LabelFor(m => m.Password)</td> <td>@Html.TextBoxFor(m => m.Password, new { @type = "password", @id = "Password", @placeholder = "Введите новый пароль", @maxlength = "30", @size = "25" })</td> </tr> <tr> <td class="label">@Html.LabelFor(m => m.ConfirmPassword)</td> <td>@Html.TextBoxFor(m => m.ConfirmPassword, new { @type = "password", @id = "ConfirmPassword", @placeholder = "Повторите ввод нового пароля", @maxlength = "25", @size = "25" })</td> </tr> <tr> <td class="label">@Html.Label("Проверочный код")</td> <td> <div class="g-recaptcha" data-sitekey="123"></div> </td> </tr> <tr> <td></td> <td><button id="change-password-button" onclick="ChangePassword();" class="add-button">Изменить пароль</button></td> </tr> </tbody> </table> </form> 

Normally it stopped working after adding google recaptcha, namely these lines in js:

 var captchaCode = $('#g-recaptcha-response').val(); ... data: { formData: formData, captcha: captchaCode }, 

and this in View:

 <div class="g-recaptcha" data-sitekey="123"></div> 

Prior to this, the second line had the following form and the controller successfully worked:

 data: formData, 

Now on the controller, everything falls on this line, because the model comes empty (determined by adding logging):

 if (!ModelState.IsValid) 

Actually, the question is how to make the model and captcha come to the controller correctly.

Thank you in advance!

  • Specify in the .ajax functions the additional contentType property : "application / json; charset = utf-8" , this is due to the fact that an incorrect ModelBinding is picked up - igosh
  • @ ivan_1988 did not help ... - tCode

1 answer 1

Try this:

 $.ajax({ type: 'POST', url: '/ChangePassword', traditional: true, contentType: "application/json; charset=utf-8", data: JSON.stringify({ formData: formData, captcha: captchaCode }), success: function (data) { var jsonResult = $.parseJSON(data); if (jsonResult.Status == 0) { $('#ChangePasswordForm').css('display', 'none'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="success"><p>Ваш пароль был успешно изменен на новый!</p></div>'); } else { $('#change-password-button').removeAttr('disabled'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="errors">' + jsonResult.Error + '</div>'); } }, error: function (data) { var jsonResult = $.parseJSON(data); $('#change-password-button').removeAttr('disabled'); $('.messageBox').css('display', 'block'); $('.messageBox').append('<div class="errors">' + jsonResult.Error + '</div>'); } }); 
  • The required model comes to the controller, but it is empty ... I can’t understand why it has all the properties null - tCode
  • It is necessary to serialize the form into the object. For example, like here - qzavyer
  • In fact, I have a string in my script that has var formData = $ ('# ChangePasswordForm'). serialize (); - tCode
  • .serialize () serializes to a string, not to an object - qzavyer