Модель не возвращает значения в контроллер из динамически добавленного содержимого? - PullRequest
0 голосов
/ 24 октября 2019

У меня есть расписание, которое можно динамически добавлять из кода, использующего Ajax. Пользователь может нажать кнопку «Добавить», и JQuery Ajax-вызов должен добавить еще один набор полей, чтобы добавить время по расписанию. По какой-то причине моя модель не возвращает какие-либо значения в контроллер, когда я нажимаю сохранить.

Я пробовал использовать другую модель, которая также включает в себя дату, время начала и время окончания, но не возвращает значения, так какЧто ж. Кажется, что значения из полей не отправляются из формы.

HTML-форма

<form asp-action="SetSchedule" asp-controller="Admin" method="post" id="addEventForm">
                <table id="scheduleTable">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Start Time</th>
                            <th>End Time</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

                <br />
                <button id="addScheduleButton" type="button">Add Schedule Time</button>
                <button id="savePendingButton" type="submit" style="margin-left:1em" hidden>Save</button>
            </form>

Контроллер:

[HttpPost]
        [Authorize(Roles = "Admin")]
        public IActionResult SetSchedule(ScheduleViewModel model)
        {
            _adminManager.SetInterviewSchedule(model);

            return RedirectToAction(nameof(ViewSchedule));
        }

Модель:

public class ScheduleViewModel
    {
        public List<Schedule> ScheduleItems { get; set; } = new List<Schedule>();

        //public InterviewInfoApplicationViewModel InterviewInfo { get; set; } = new InterviewInfoApplicationViewModel();
    }

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

        public DateTime DateAvailable { get; set; }

        [Required]
        public DateTime StartTime { get; set; }

        [Required]
        public DateTime EndTime { get; set; }

        public bool IsSelected { get; internal set; }
    }

Поля, добавляемые на страницу вызова ajax:

@model Ambassadors.Managers.ViewModels.Admin.Schedule

@{
    string rowClass = "pendingScheduleRow";
}

    <tr class="@rowClass" style="margin-top:1em">
        <td>
            @Html.ValidationMessageFor(x => x.DateAvailable)
            <input type="text" asp-for="DateAvailable" class="datepickerInput" />
        </td>
        <td>
            @Html.ValidationMessageFor(x => x.StartTime)
            <input type="text" asp-for="StartTime" class="timepickerInput" />
        </td>
        <td>
            @Html.ValidationMessageFor(x => x.EndTime)
            <input type="text" asp-for="EndTime" class="timepickerInput" />
        </td>
        <td>
            <a class="tooltip deletePendingSchedule" title="Remove Schedule Time" style="cursor:pointer">
                <span class="wdn-icon-cancel" aria-hidden="true"></span><span class="wdn-text-hidden">cancel icon</span>
            </a>
        </td>
    </tr>

Сценарий:

    require(['jquery', 'jqueryui'], function ($, jqueryui) {

        $(function () {
  $('body').on('focus', ".datepickerInput", function () {
                    $(this).datepicker({
                        controlType: "select",

                    });
                });

                $('body').on('focus', ".timepickerInput", function () {
                    $(this).timepicker({
                        timeFormat: "hh:mm tt",
                        interval: 5,
                        dropdown: true,
                        scrollbar: true
                    });
                });

                $("#addScheduleButton").click(function () {
                    var nextIndex = $(".pendingScheduleRow").length;

                    $.ajax({
                        url: "/Admin/AddScheduleItem",
                        type: 'POST',
                        data: {
                            index: nextIndex
                        },
                        success: function (results) {
                            $("table#scheduleTable tbody").append(results);
                            $("#savePendingButton").show();
                        }
                    });
                });

                $("#scheduleTable").on("click", ".deletePendingSchedule", function () {

                    var closestRow = $(this).closest("tr");

                    $(closestRow).hide();

                    var visibleRows = $(".pendingScheduleRow:visible").length;

                    if (visibleRows === 0) {

                        $("#savePendingButton").hide();
                    }

                });

        });

    });

Модель должна возвращать DateAvailable, StartTime и EndTimes в контроллер.

1 Ответ

0 голосов
/ 25 октября 2019

Ваше действие получает тип модели ScheduleViewModel, у которого есть свойство List<Schedule>, в то время как ваш взгляд asp-for="DateAvailable" не привязан к ScheduleViewModel и не привязан к List<Schedule>.

См. Мою демонстрационную версию ниже:

1.AddScheduleItem - действие для возврата index в частичное представление

public IActionResult AddScheduleItem(string index)
    {
        var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) 
                         { 
                            { "index", index }
                         };
        PartialViewResult result = new PartialViewResult()
        {
            ViewName = "YourPartialViewName",
            ViewData = myViewData,
        };

        return result;

    }

2.YourPartailView:

@model ScheduleViewModel

@{
    string rowClass = "pendingScheduleRow";
    int index = Int32.Parse(@ViewData["index"].ToString());
}

<tr class="@rowClass" style="margin-top:1em">
    <td>
        @Html.ValidationMessageFor(x => x.ScheduleItems[index].DateAvailable)
        <input asp-for="ScheduleItems[index].DateAvailable" class="datepickerInput" />
    </td>
    <td>
        @Html.ValidationMessageFor(x => x.ScheduleItems[index].StartTime)
        <input asp-for="ScheduleItems[index].StartTime" class="timepickerInput" />
    </td>
    <td>
        @Html.ValidationMessageFor(x => x.ScheduleItems[index].EndTime)
        <input asp-for="ScheduleItems[index].EndTime" class="timepickerInput" />
    </td>
    <td>
        <a class="tooltip deletePendingSchedule" title="Remove Schedule Time" style="cursor:pointer">
            <span class="wdn-icon-cancel" aria-hidden="true"></span><span class="wdn-text-hidden">cancel icon</span>
        </a>
    </td>
</tr>
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...