1

I want to know how to trigger the model validation in bootstrap modal pop up before submitting? I want to trigger the required and remoteattribute validation from my modal pop up

Here is my model code:

    public class Employee
    {
        public int Id { get; set; }

[Required]
        [Remote("CheckFirstName", "Employees", ErrorMessage = "FirstName already exists.")]
        public string FirstName { get; set; }

        //code here
    }

My controller code:

    public IActionResult Create()
        {
            Employee emp = new Employee();
            return PartialView("_EmployeePartial", emp);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,MI")] Employee employee)
        {
            //code here
            return View(employee);
        }

[AcceptVerbs("Post", "Get")]
public IActionResult CheckFirstName(string fname){
//code here
}

My employeepartial code:

@model CrudApp.Models.Employee
<!-- Modal -->
<div class="modal fade" id="addEmployee" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <form asp-action="Create">
                    //code here
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-save="modal">Save changes</button>
            </div>
        </div>
    </div>
</div>

Code to call modal:

<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addEmployee"
        data-url="@Url.Action("Create")">Create</button>

JS Code:

    var PlaceHolderElement = $('#PlaceHolderHere');
    $('button[data-toggle="ajax-modal"]').click(function (event) {

        var url = $(this).data('url');
        $.get(url).done(function (data) {
            PlaceHolderElement.html(data);
            PlaceHolderElement.find('.modal').modal('show');
        });
    });

    PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {

        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var sendData = form.serialize();
        $.post(actionUrl, sendData).done(function (data) {
            PlaceHolderElement.find('.modal').modal('hide');
        });
    });
Asdf1234567
  • 476
  • 1
  • 10
  • 25

2 Answers2

0

You are triggering the CheckFirstName Action which doesn't exist in your controller.

public IActionResult CheckFirstName(string FirstName)
{
   // code to validate the FirstName
   
   return Json(result); //return result in json example your validation message.
}

This will trigger when you enter the input in the FirstName textbox.

Safyan Yaqoob
  • 444
  • 3
  • 11
  • Sorry, i just forgot to include in my code but it exist actually. thanks – Asdf1234567 Jun 27 '21 at 08:20
  • 1
    Ok. But I have noticed your parameter name in CheckFirstName Action does not match with your modal property means FirstName doesn't match with fname. Remote validation will not trigger if the parameter name is different – Safyan Yaqoob Jun 27 '21 at 09:03
0

Since the Employee Create Form is dynamic added in the main form and you are submitting the form via JQuery method, to trigger the validation, you have to set up the client-side validation on the form (after showing the popup model). Check the following code:

Index.cshtml (main page):

<div id="PlaceHolderHere"></div>

<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addEmployee"
        data-url="@Url.Action("Create")">
    Create
</button>

@section Scripts{   
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        $(function () {
            var PlaceHolderElement = $('#PlaceHolderHere');
            $('button[data-toggle="ajax-modal"]').click(function (event) {

                var url = $(this).data('url');
                $.get(url).done(function (data) {
                    PlaceHolderElement.html(data);
                    PlaceHolderElement.find('.modal').modal('show');
                    var form = PlaceHolderElement.find('.modal').find("form");
                    //enable client side validation.
                    $.validator.unobtrusive.parse(form);
                });
            });

            PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {

                var form = $(this).parents('.modal').find('form');
                //check whether the form is valid or not
                if (form.valid()) {
                    var actionUrl = form.attr('action');
                    var sendData = form.serialize();

                    $.post(actionUrl, sendData).done(function (data) {
                        PlaceHolderElement.find('.modal').modal('hide');
                    });
                }
                
            });
        });
    </script>
}

The controller code as below:

    public IActionResult Create()
    {
        Employee emp = new Employee();
        return PartialView("_EmployeePartial", emp);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,MI")] Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction(nameof(Index));
        }
        //code here
        return View(employee);
    }

    [AcceptVerbs("Post", "Get")]
    public IActionResult CheckFirstName(string FirstName)
    {
        var emplist = new List<string>() { "AA", "BB", "CC" };

        if (emplist.Contains(FirstName))
        {
            return Json(false);
        }

        //code here
        return Json(true);
    }

Then, the result like this:

enter image description here

[Note]: To enable the client-side validation, we should add the client-side validation script references like this: @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}. More detail information, see Client-side validation.

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30