0

I'm trying to validate fields with ValidationMessageFor, and everything works fine if you submit the form using Html.Beginform, but if I use an AJAX query, then validations no longer work. My Code View:

@model AutoStore.Domain.Core.Client

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

<style>
    html,
    body {
        height: 100%;
    }

    body {
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        padding-top: 40px;
        padding-bottom: 40px;
    }

    .form-signin {
        width: 100%;
        max-width: 330px;
        padding: 15px;
        margin: auto;
    }

    .input-group-text {
        border-top-left-radius: 30px;
        border-bottom-left-radius: 30px;
    }

    .form-control {
        border-radius: 30px;
    }
</style>

@Html.ActionLink("Главная", "Index")

@using (Html.BeginForm())
{
    <div class="container">
        <div class="form-signin">
            <div class="form-group">
                @Html.LabelFor(i => i.CSurname, "Фамилия")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                        @Html.EditorFor(i => i.CSurname, new { htmlAttributes = new { @id = "txtSurname", @class = "form-control", @placeholder = "Введите фамилию" } })
                    </div>
                    @Html.ValidationMessageFor(i => i.CSurname, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(i => i.CName, "Имя")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                        @Html.EditorFor(i => i.CName, new { htmlAttributes = new { @id = "txtName", @class = "form-control", @placeholder = "Введите имя" } })
                    </div>
                    @Html.ValidationMessageFor(i => i.CName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(i => i.CPatronymic, "Отчество")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                        @Html.EditorFor(i => i.CPatronymic, new { htmlAttributes = new { @id = "txtPatr", @class = "form-control", @placeholder = "Введите отчество" } })
                    </div>
                    @Html.ValidationMessageFor(i => i.CPatronymic, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(i => i.Login, "Логин")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-user fa" aria-hidden="true"></i></span>
                        @Html.EditorFor(i => i.Login, new { htmlAttributes = new { @id = "txtLogin", @class = "form-control", @placeholder = "Введите логин" } })
                    </div>
                    @Html.ValidationMessageFor(i => i.Login, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(i => i.Password, "Пароль")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-lock fa" aria-hidden="true"></i></span>
                        @Html.PasswordFor(i => i.Password, new { @id = "txtPass", @class = "form-control", @placeholder = "Введите пароль" })
                    </div>
                    @Html.ValidationMessageFor(i => i.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(i => i.Email, "E-Mail")
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
                        @Html.EditorFor(i => i.Email, new { htmlAttributes = new { @id = "txtMail", @class = "form-control", @placeholder = "Введите e-mail", @type = "email" } })
                    </div>
                    @Html.ValidationMessageFor(i => i.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <input id="btnAdd" type="submit" class="btn btn-success btn-block" value="Добавить" />
        </div>
    </div>
}

<script type="text/javascript">
$(document).ready(function () {
    $('form').validate({
        submitHandler: function (form) {
            $.ajax({
                type: "POST",
                url: "/Authorization/Registration",
                data: $(form).serialize(),
                success: function (result) {
                    $(location).attr('href', result.URL);
                }
            });
        }
    });
});

Controller:

[HttpPost]
        public ActionResult Registration(Client client)
        {
            if (ModelState.IsValid)
            {
                /*unitOfWork.Clients.Create(client);
                unitOfWork.Save();*/
                var url = new { URL = Url.Content("/Authorization/Index") + "#success" };
                return Json(url);
            }

            return View();
        }

_Layout:

@Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js")
    @Scripts.Render("~/scripts/jquery.validate.min.js")
    @Scripts.Render("~/scripts/jquery.validate.unobtrusive.min.js")

    <div class="container body-content">
        @RenderBody()
    </div>

With this option validation works, but only after the form is submitted. And after performing the Ajax request, it does not redirect me to the address that I collect in the controller, but instead simply displays this address as a string on the screen. And if instead of using jquery Ajax.Beginform, then, validation does not work when the form has already been submitted, but immediately after entering incorrect data in the input field. enter image description here

Андрей
  • 143
  • 1
  • 7
  • You need to use `jQuery.validate` library as provided in [this issue](https://stackoverflow.com/questions/14005773/use-asp-net-mvc-validation-with-jquery-ajax) and set validation rules depending on requirements. – Tetsuya Yamamoto Jan 03 '19 at 08:00
  • Try: https://stackoverflow.com/a/52208543/594235 – Sparky Jan 05 '19 at 19:35
  • @Sparky, i try it's, but not work. I give an example of my code at the end of the question. – Андрей Jan 06 '19 at 16:29
  • @Sparky It turned out to make so that validation would work immediately when entering data into text fields. Forgot to add first `$(document).ready`, but there was another problem. After performing the Ajax request, the program does not transfer to the page with the address I return to the controller, but simply writes this address as a string on the screen. The screenshot at the end of the question. – Андрей Jan 06 '19 at 17:32
  • @Sparky And what is most interesting, in the debugging of the client, the code does not even enter the block of the succession. Then I decided to check on the server `Request.IsAjaxRequest` and result 'false'. Why the server does not consider my request, Ajax request. And how to fix it? What's wrong with my code? – Андрей Jan 06 '19 at 17:33
  • 1
    No idea what you're talking about. If you want to transfer to a new page after submit, then Ajax is pointless. Standard form submission redirects/reloads. Ajax does not redirect/reload, which is the whole point of Ajax... to do data transmission to server without redirecting or reloading the page. – Sparky Jan 06 '19 at 17:42
  • @Sparky, yes, but I need, depending on the result of the execution, to return the desired action, therefore, I use Ajax. – Андрей Jan 06 '19 at 17:54
  • @Sparky and if i will use `Ajax.Beginform` Everything will work to the end as it should, and for your option, the server for some reason does not consider the request, the Ajax as a request, and therefore after trying to redirect to another page, this does not work. – Андрей Jan 06 '19 at 17:55
  • @Sparky Why doesn't the success function work in your version of the query? – Андрей Jan 06 '19 at 17:56
  • @Sparky, I understood what was going on, I did not send an ajax request, but a normal request. How to make it so that the Ajax request is sent? – Андрей Jan 06 '19 at 18:18
  • @Sparky, maybe it's because I haven't written `return false`? But I tried it with him, and still it is not the Ajax request that is sent. – Андрей Jan 06 '19 at 18:20

0 Answers0