0

I have a main view on which there are 2 tables. Using ajax, I invoke a modal textbox window. I fill them in and click add. Records were added normally when the modal window was called not by ajax but simply by a button with the necessary html parameters, and the partialview itself was called on the main form with the help of html.partial. I redid the call to ajax request, the ajax button request to add has stopped working. I can not understand what's the matter, please tell me what is wrong. Here is my code. main view:

@{
    ViewBag.Title = "Index";
}

@model IEnumerable<AjaxTest.Models.Book>

<h2>Каталог книг</h2>

<input id="modRender" type="submit" value="Добавить" />

<body>
    <div id="result"></div>
    <div>
        <table id="tab" class="table table-bordered">
            <thead>
                <tr>
                    <th>Название</th>
                    <th>Автор</th>
                    <th>Цена</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(i => item.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Author)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Price)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</body>

<h2>Список пользователей</h2>

<body>
    <div>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Имя</th>
                    <th>Фамилия</th>
                    <th>Возраст</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewBag.Users as List<AjaxTest.Models.User>)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(i => item.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Surname)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Age)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</body>

<div id="result"></div>

@section scripts{
    <script type="text/javascript">
        $('#modRender').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/ModalCreate",
                success: function (data) {
                    $('#result').html(data);
                    $('#mod').modal('show');
                }
            });
        });

        $('#btnAdd').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/Create",
                data: {
                    "Name": $('#txtName').val(),
                    "Author": $('#txtAuthor').val(),
                    "Price": $('#txtPrice').val()
                },
                success: function (data) {
                    $('#tab tbody').append(data);
                }
            });
        });

        $("#result").on('hidden.bs.modal', function () {
            $('#mod').remove();
        });
    </script>
}

view modal window:

<div id="mod" class="modal fade" >
    <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">Новая книга</h4>
            </div>
            <div class="modal-body">
                <table>
                    <tr>
                        <td><p>Название</p></td>
                        <td><input type="text" id="txtName" /></td>
                    </tr>
                    <tr>
                        <td><p>Автор</p></td>
                        <td><input type="text" id="txtAuthor" /></td>
                    </tr>
                    <tr>
                        <td><p>Цена</p></td>
                        <td><input type="text" id="txtPrice" /></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button>
                <button id="btnAdd" type="submit" data-dismiss="modal" class="btn btn-primary">Добавить</button>
            </div>
        </div>
    </div>
</div>

Controller:

Context db = new Context();

        [HttpGet]
        public ActionResult Index()
        {
            List<Book> books = db.Books.ToList();
            List<User> users = db.Users.ToList();
            ViewBag.Users = users;

            return View(books);
        }

        [HttpPost]
        public ActionResult Create(Book book)
        {
            db.Books.Add(book);
            db.SaveChanges();

            return PartialView(book);
        }

        [HttpPost]
        public ActionResult ModalCreate()
        {
            return PartialView();
        }
Андрей
  • 133
  • 7
  • Can you check possible errors in browser console? Did the AJAX request reach the controller during debug? Your AJAX code seem fine to me, probably something wrong happened when second AJAX request initialized. – Tetsuya Yamamoto Dec 21 '18 at 05:48
  • Your HTML doesn't look right, you have elements outside the `` that should be inside. – Barmar Dec 21 '18 at 05:51
  • Also using multiple `` tags to separate display values and inputs are not recommended, just use one `` tag and put other HTML elements there. – Tetsuya Yamamoto Dec 21 '18 at 05:55
  • @TetsuyaYamamoto The fact of the matter is that the Ajax request is not even executed on the client and not any errors. And the code itself does not enter the controller either. But if I did as I had before (I described the first option at the beginning of the question) in that case there was only 1 Ajax request and everything worked out normally. – Андрей Dec 21 '18 at 06:18
  • @Barmar yes, i know. I change it, but my mistake is not related to this. And I would like to fix it. – Андрей Dec 21 '18 at 06:22
  • I don't think the problem is related to it. I couldn't figure out what's causing your problem, or I would have posted an answer. – Barmar Dec 21 '18 at 06:23
  • Are you doing anything that replaces the modal div dynamically? You might need to see https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Dec 21 '18 at 06:25
  • @Barmar, thanks, but i want use modal window, but thanks for this option. – Андрей Dec 21 '18 at 06:30
  • I never said not to use a modal window. – Barmar Dec 21 '18 at 06:31
  • @Barmar, sorry, i got you wrong. – Андрей Dec 21 '18 at 06:35
  • @Barmar in ajax requst replaces my modal div, need me html code `$('#result').html(data);` – Андрей Dec 21 '18 at 06:36
  • Then use event delegation as shown in that question. – Barmar Dec 21 '18 at 06:37
  • @Barmar, very thanks, it's work, but I can not understand why the code did not work as before. – Андрей Dec 21 '18 at 06:42
  • @Barmar new code `$(document).on('click', '#btnAdd', function () {`, older `$('#btnAdd').on('click', function () {` – Андрей Dec 21 '18 at 06:42
  • @Barmar why???? – Андрей Dec 21 '18 at 06:43
  • You bound the click handler to the original `#btnAdd` button. Then you overwrite the DIV with new HTML, all the old event handlers were lost. – Barmar Dec 21 '18 at 06:43
  • @TetsuyaYamamoto solved the problem with the help of such a code `$(document).on('click', '#btnAdd', function () {` – Андрей Dec 21 '18 at 06:43
  • @Barmar, and in the old version it turns out to work because my page with the help of Html.Partial added the necessary code to the page right away? – Андрей Dec 21 '18 at 06:45

0 Answers0