привязка модели ядра MVC asp.net с повторителем jquery - PullRequest
0 голосов
/ 20 марта 2019

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

Вот моя модель.

public class SuggestionCreateEditViewModel
{
    public Guid[] DetectionId { get; set; }

    public SuggestionCreateEditRepeatedModel[] Repeated { get; set; }

}
public class SuggestionCreateEditRepeatedModel
{
    public Guid To { get; set; }

    public string Description { get; set; }

    public DateTime Deadline { get; set; }
}

Форма, Для краткости я удалил много частей формы

<div class="col-lg-9 col-md-9 col-sm-12">
    <select asp-for="DetectionId" asp-items="ViewBag.AllDetections" class="m-bootstrap-select m_selectpicker toValidate" 
            multiple data-actions-box="true" data-width="100%"></select>
</div>
<div class="col-lg-9 col-md-9 col-sm-12 input-group date">
    <input name = "Repeated.Deadline" type="text" readonly class="form-control toValidate dtDueDate" />
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
    <textarea name = "Repeated.Description" class="form-control toValidate txtSuggestion" type="text" >
    </textarea>
</div>

после добавления нового повторяющегося раздела в форму и перед его отправкой на сервер, если я form.serailizeArray() возвращает коллекцию, как показано ниже (какой, по моему мнению, повторитель формы jquery динамически формирует имена)

{name: "DetectionId", value: "afca1b82-0455-432e-c780-08d6ac38b012"}
{name: "[0][Repeated.To][]", value: "b1176b82-1c25-4d13-9283-df2b16735266"}
{name: "[0][Repeated.Deadline]", value: "04/04/2019"}
{name: "[0][Repeated.Description]", value: "<p>test 1</p>"}
{name: "[1][Repeated.To]", value: "188806d8-202a-4787-98a6-8dc060624d93"}
{name: "[1][Repeated.Deadline]", value: "05/04/2019"}
{name: "[1][Repeated.Description]", value: "<p>test 2</p>"}

и мой контроллер

[HttpPost]
public IActionResult CreateSuggestion(SuggestionCreateEditViewModel model, IFormFile[] documents)
        {...
Контроллер

не может получить Repeated, только DetectionId. Как мне сформировать мою модель, чтобы получить данные?

Ответы [ 2 ]

1 голос
/ 21 марта 2019

Вот рабочая демонстрация для jquery.repeater.js, обратите внимание на эту строку <div data-repeater-list="Repeated">, которая отформатирует поле как name="Repeated[0][Description]"

@model TestCore.Models.SuggestionCreateEditViewModel
@{
    ViewData["Title"] = "Contact";
}

<form class="repeater" asp-action="CreateSuggestion" method="post">
    <!--
        The value given to the data-repeater-list attribute will be used as the
        base of rewritten name attributes.  In this example, the first
        data-repeater-item's name attribute would become group-a[0][text-input],
        and the second data-repeater-item would become group-a[1][text-input]
    -->
    <div data-repeater-list="Repeated">
        <div data-repeater-item>
            <div class="col-lg-9 col-md-9 col-sm-12">
                <select asp-for="DetectionId" asp-items="ViewBag.AllDetections" class="m-bootstrap-select m_selectpicker toValidate"
                        multiple data-actions-box="true" data-width="100%"></select>
            </div>
            <div class="col-lg-12 col-md-12 col-sm-12">
                <textarea name="Description" class="form-control toValidate txtSuggestion" type="text">
                </textarea>
            </div>
        </div>
    </div>
    <input data-repeater-create type="button" value="Add" />
    <input type="submit" value="Submit"/>
</form>
@section Scripts{
    <!-- Import repeater js  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.js"></script>
    <script>
        $(document).ready(function () {
            $('.repeater').repeater({
                // (Optional)
                // start with an empty list of repeaters. Set your first (and only)
                // "data-repeater-item" with style="display:none;" and pass the
                // following configuration flag
                initEmpty: true,

                // (Optional)
                // "show" is called just after an item is added.  The item is hidden
                // at this point.  If a show callback is not given the item will
                // have $(this).show() called on it.
                show: function () {
                    $(this).slideDown();
                },
                // (Optional)
                // "hide" is called when a user clicks on a data-repeater-delete
                // element.  The item is still visible.  "hide" is passed a function
                // as its first argument which will properly remove the item.
                // "hide" allows for a confirmation step, to send a delete request
                // to the server, etc.  If a hide callback is not given the item
                // will be deleted.
                hide: function (deleteElement) {
                    if (confirm('Are you sure you want to delete this element?')) {
                        $(this).slideUp(deleteElement);
                    }
                },

                // (Optional)
                // Removes the delete button from the first list item,
                // defaults to false.
                isFirstItemUndeletable: true
            })
        });    
    </script>
}
0 голосов
/ 20 марта 2019

, судя по всему, контроллер не может привязать свойства повторителя обратно к вашей модели представления, потому что наименование размещенного контента не совпадает с именами в вашей модели представления (как упомянул Тофер).

DetectionId назван правильно, потому что имя свойства совпадает, а не является массивом.

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

При этом вы можете попробовать изменить формат имени на: Повтор [0]. На

Это должно соответствоватьс вашим контроллером и правильно связать.

Для получения дополнительной информации о связывании, пожалуйста, смотрите https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

...