skip to Main Content

I have very strange problem I have main form with datatable and edit details buttons in every row when i click on Edit button opens modal partialview and load data from table but when i click to save data validation doesnt work at all. When i click New button everything works fine and i dont know what goes wrong. I added

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

in my main view and

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

in partial and result is the same

Main View


    $(document).ready(function ()
            {
            dataTable = $('#userTable').DataTable({
                    "responsive": "true",
                    "ajax": {
                    "type" : "GET" ,
                    "url" : "@Url.Action("GetData","Customers")" ,
                    "datatype" : "json"
                    },
                    "columns":
                    [
                    { "data": "FirstName"},
                    {
                      "data": "Id", "render": function (data) {
                            return '<a class="btn btn-danger" onclick="Details('' + data + '')" style="margin-right: 12px"><span class="glyphicon glyphicon-th-list" style=" margin-right: 2px;"></span>Details</a><a data-toggle="modal" data-target="#myModal" class="btn btn-success" onclick="Edit('' + data + '')" style="margin-right: 12px"><span class="glyphicon glyphicon-pencil" style=" margin-right: 2px;"></span>Edit</a>';
                      }
                    }
                    ],
                    "language": {
                        "processing": "<img src='https://gph.is/2gESFHh' />",
                        "emptytable": "Няма данни за изжедане. Може да натиснете бутона <b> Нов </b>"
                    },
                });
        });

        function Edit(Id) {
            //if (confirm("Наистина ли искате да промените този запис?")) {
                $.ajax({
                    type : 'Get' ,
                    url: '@Url.Action("AddOrEditPartial","Customers")/' + Id,
                    data: { Id: Id }
                }).done(function(result) {
                    $('#modbody').html(result);
                });
            //}
            }
    </script>


}

<h2>Users</h2>

<div class="col-md-12" style="background-color: white; padding-top: 20px; padding-bottom: 20px; border-radius: 3px;">
<a data-toggle="modal" data-target="#myModal" class="btn btn-success" style="margin-bottom: 12px; margin-top:12px "><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
    <table id="userTable" class="display" style="width: 100%;">
        <thead>
            <tr>
                <th>
                    Name:
                </th>
                <th></th>
            </tr>
        </thead>
    </table>

    <div class="modal fade" id="myModal" role="dialog" style="margin-top: 100px;">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Users</h4>
                </div>
                <div class="modal-body" id="modbody">
                    @Html.Partial("AddOrEditPartial")
                </div>
            </div>
        </div>
    </div>

</div>
<table class="table" id="userTable">
</table>

PartialView

@model Sfuk1.Models.Customer

<div class="panel-group">
    <div class="panel-default">
        <div class="panel panel-success">
            <div class="panel-body" id="panbody">
                <div class="col-sm-10 col-sm-offset-1">
                    @using (Html.BeginForm("AddOrEditPartial", "Customers", FormMethod.Post, new { enctype = "multipart/for-data", id = "formsubmit" }))
                    {
                        @Html.AntiForgeryToken()

                        <div class="form-horizontal">
                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="form-group">
                                @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
                                <div class="col-md-10">
                                    @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-offset-2 col-md-10">
                                    <input type="submit" value="Save" class="btn btn-success" id="btnSubmit" onclick="Validation()" />
                                </div>
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>
@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
<script>
    var Validation = function () {
        debugger
        var data = $("formsubmit").serialize;
        if (!$("formsubmit").valid()) {
            console.log(false);
            return false;
        }
    }

</script>

2

Answers


  1. Chosen as BEST ANSWER

    I installed unobtrusive-ajax and also added it in main scripts


  2. @section scripts from partial view will not work in Main View, as the page is already rendered, you need to use @section scripts in main view.

    Also, you need refer unobtrusive validation js file in Main view not in partial view "<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>"

    Consider placing all JS code in Main View.

    one more point instead of using HTML.BeginForm, try using Ajax.BeginForm

    Sample Razor/HTML code ( Main View)

    @{
       ViewBag.Title = "Create";
      }
    
       <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
         Create Blog
     </button>
    <!-- Modal -->
     @using (Ajax.BeginForm("SaveBlog", "Home", new AjaxOptions() { HttpMethod = "POST",UpdateTargetId = "frmEmp"  }))
         {
     <div>
         <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
              <div class="modal-dialog" role="document">
                  <div class="modal-content">
                       <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                               <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title" id="myModalLabel">Create New Blog</h4>
                      </div>
                     <div class="modal-body" id="frmEmp">
                        @Html.Partial("_Blog")
                     </div>
                      <div class="modal-footer">
                         <input type="submit" class="btn btn-primary" value="Submit" />
                       </div>
                  </div>
              </div>
          </div>
       </div>
      }
    

    Partial View;

    @model BootstrapModalPopUp.Models.Blog
    
    @Html.AntiForgeryToken()
    @if (ViewBag.Message != null)
    {
    <span class="text-success">@ViewBag.Message</span>
    }
      <span class="alert-danger">
        @Html.ValidationSummary()
      </span>
      <div class="form-group">
       @Html.LabelFor(model => model.Name)
      @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
      </div>
     <div class="form-group">
       @Html.LabelFor(model => model.CategoryName)
        @Html.TextBoxFor(model => model.CategoryName, new { @class = "form-control" })
      </div>
    

    Required JS files in Main View

     <script src="~/Scripts/jquery-1.10.2.min.js"></script>
     <script src="~/Scripts/bootstrap.min.js"></script>
    
     <script src="~/Scripts/jquery.validate.min.js"></script>
     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
     <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    

    Source: https://qawithexperts.com/article/asp.net/validate-pop-up-modal-using-ajaxbeginform-in-c-mvc/52
    You can also check complete working sample or download it from above link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search