简体   繁体   English

Model 列表返回为 null 从视图到 controller Z9E0DA8438E1E38A1C30F4B76ZCE3 核心

[英]Model List returning as null from view to controller ASP.NET Core MVC

I'm having trouble with a list within my model returning as null even tho in the view it clearly has some value.我的 model 中的列表返回为 null 时遇到问题,即使在视图中它显然具有一些价值。

I had trouble trying to add objects to my model's list, someone helped me and my problem was half solved.我在尝试将对象添加到模型列表时遇到了麻烦,有人帮助了我,我的问题解决了一半。 This is the code I came up with after the help这是我在帮助后想出的代码

My view:我的观点:

@model ActivityForm

@{
    ViewData["Title"] = "Activity Details";
}

<section class="my-sm-5">
    <div class="container">
        <div class="section-header d-flex mb-5">
            <h1 class="h-02 flex-grow-1">Activity Details</h1>
        </div>
        <div class="row">
            <div class="col-md-7">
                <div class="section-header d-flex mb-5">
                    <h1 class="h-04 flex-grow-1">Form</h1>
                </div>
                <form id="form" class="row g-3 w-90" asp-action="Create">
                    <div class="col-md-12">
                        <label asp-for="Name" class="form-label">@Html.DisplayNameFor(model => model.Name)</label>
                        <input asp-for="Name" type="text" class="form-control" id="inputEmail4"
                            placeholder="@Html.DisplayNameFor(model => model.Name)">
                        <span asp-validation-for="Name" class="invalid-feedback"></span>
                    </div>
                    <div class="col-12">
                        <label asp-for="Description" class="form-label">@Html.DisplayNameFor(model =>
                            model.Description)</label>
                        <textarea asp-for="Description" class="form-control" id="exampleFormControlTextarea1" rows="5"
                            placeholder="@Html.DisplayNameFor(model => model.Description)"></textarea>
                        <span asp-validation-for="Description" class="invalid-feedback"></span>
                    </div>
                    <div class="col-md-4">
                        <label asp-for="StartDate" class="form-label">@Html.DisplayNameFor(model =>
                            model.StartDate)</label>
                        <input asp-for="StartDate" type="date" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.StartDate)">
                        <span asp-validation-for="StartDate" class="invalid-feedback"></span>
                    </div>
                    <div class="col-md-4">
                        <label asp-for="EndDate" class="form-label">@Html.DisplayNameFor(model => model.EndDate)</label>
                        <input asp-for="EndDate" type="date" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.EndDate)">
                        <span asp-validation-for="EndDate" class="invalid-feedback"></span>
                    </div>
                    <div class="col-md-4 mb-6">
                        <label asp-for="Points" class="form-label">@Html.DisplayNameFor(model => model.Points)</label>
                        <input asp-for="Points" type="number" class="form-control"
                            placeholder="@Html.DisplayNameFor(model => model.Points)">
                        <span asp-validation-for="Points" class="invalid-feedback"></span>
                    </div>
                    <div class="col-8 d-grid gap-2">
                        <a class="btn btn-primary mb-2" data-bs-toggle="modal" data-bs-target="#add-award">Add award</a>
                        <div class="row">
                            <div class="col-md-6">
                                <a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
                                    data-bs-target="#cancel-activity">Cancel</a>
                            </div>
                            <div class="col-md-6">
                                <a class="btn btn-outline-primary w-100" data-bs-toggle="modal"
                                    data-bs-target="#post-activity">Post Activity</a>
                            </div>
                        </div>
                    </div>

                    <div class="modal" id="add-award" tabindex="-1">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content br-20 pd-20">
                                <div class="modal-header justify-content-center">
                                    <h5 class="modal-title h-04 text-prim-color">Award details</h5>
                                </div>
                                <div class="row g-3">
                                    <div class="modal-body">
                                        <div class="row g-3">
                                            <div class="col-md-12">
                                                <label asp-for="Award.Name" class="form-label">Name</label>
                                                <input asp-for="Award.Name" type="text" class="form-control"
                                                    id="award-name">
                                            </div>
                                            <div class="col-12">
                                                <label asp-for="Award.Description" for="inputAddress"
                                                    class="form-label">Description</label>
                                                <textarea asp-for="Award.Description" class="form-control"
                                                    id="award-description" rows="5"></textarea>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer justify-content-center">
                                        <button type="button" class="btn btn-outline-primary w-100"
                                            data-bs-dismiss="modal">Close</button>
                                        <input class="btn btn-primary w-100" type="submit" value="Confirm"></input>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="col-md-5">
                <div class="section-header d-flex mb-5">
                    <h1 class="h-04 flex-grow-1">Awards</h1>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">Award name</th>
                            <th scope="col">Description</th>
                            <th scope="col"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @if (Model.Awards != null)
                        {
                            foreach (var item in Model.Awards)
                            {
                                <tr>
                                    <td>@item.Name</td>
                                    <td>@item.Description</td>
                                    <td>
                                        <a class="btn btn-outline-primary btn-sm">Edit</a>
                                        <a class="btn btn-outline-primary btn-sm">Remove</a>
                                    </td>
                                </tr>
                            }
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>

Method in controller: controller中的方法:

        [HttpPost]
        public async Task<IActionResult> Create(ActivityForm data)
        {
            var award = data.Award;

            if (award.Name != null && award.Description != null)
            {
                if (data.Awards == null) data.Awards = new List<AwardForm>();

                data.Awards.Add(new AwardForm { Name = award.Name, Description = award.Description });

                data.Award.Name = "";
                data.Award.Description = "";

                return View(data);
            }


            if (!ModelState.IsValid)
            {
                return View(data);
            }

            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            await service.NewActivityAsync(data, userId);
            return RedirectToAction(nameof(Index));
        }

Model Model

    public class ActivityForm
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        public int Points { get; set; }

        public AwardForm Award { get; set; }

        public List<AwardForm> Awards { get; set; }
    }

Everything was now working as intended but I had one more issue left.现在一切都按预期工作,但我还有一个问题。 When I try to add another Award to the list, the list is returned to the controller method as null.当我尝试向列表中添加另一个奖项时,列表返回到 controller 方法,为 null。

I'm not really sure if the issue is related to binding, I have noticed that every other value is bound and is returning the expected value except the list which is not bound.我不太确定问题是否与绑定有关,我注意到所有其他值都已绑定,并且除了未绑定的列表之外,它正在返回预期值。

The list binding context should include indexes to work properly.列表绑定上下文应该包括索引才能正常工作。

Try to change you foreach like below:尝试改变你的foreach如下:

int i=0; @* indexing value *@
foreach (var item in Model.Awards)                        
{
    @Html.Hidden("Awards[" + i + "].Name", item.Name)
    @Html.Hidden("Awards[" + i + "].Description", item.Description)
    <tr>
        <td>@item.Name</td>
        <td>@item.Description</td>
        <td>
            <a class="btn btn-outline-primary btn-sm">Edit</a>
            <a class="btn btn-outline-primary btn-sm">Remove</a>
        </td>
    </tr>
    i++;
}

Change the foreach loop to:foreach循环更改为:

<tbody>
    @if (Model.Awards != null)
    {
        @for (var i = 0; i < Model.Awards.Count; i++)
        {
            <input type="hidden" asp-for="@Model.Awards[i].Name" />
            <input type="hidden" asp-for="@Model.Awards[i].Description" />
            <tr>            
                <td>@Model.Awards[i].Name</td>
                <td>@Model.Awards[i].Description</td>
                <td>
                    <a class="btn btn-outline-primary btn-sm">Edit</a>
                    <a class="btn btn-outline-primary btn-sm">Remove</a>
                </td>
            </tr>
        }
    }
</tbody>

This has same effect to what @Victor suggested but using input tag helper instead of html helper.这与@Victor建议的效果相同,但使用输入标签助手而不是 html 助手。

Documentation for binding model to a collection: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#collections-1将 model 绑定到集合的文档: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#collections-1

Also your form should wrap around both Form and Awards sections:此外,您的表格应该包含表格奖项部分:

<form id="form" class="row g-3 w-90" asp-action="Create">
    <div class="col-md-7">
        <div class="section-header d-flex mb-5">
            <h1 class="h-04 flex-grow-1">Form</h1>
        </div>
        ...
    </div>
    <div class="col-md-5">
        <div class="section-header d-flex mb-5">
            <h1 class="h-04 flex-grow-1">Awards</h1>
        </div>
        ...
    </div>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core MVC - 无法使用视图返回模型 - ASP.NET Core MVC - Trouble returning model with view 将两个或多个参数从 model 视图传递到 EF Core / ASP.NET Core MVC 应用程序中的 controller - Passing two or more parameters from model view to controller in EF Core / ASP.NET Core MVC application 未将数据列表返回到 ASP.NET Core MVC 中的索引视图中 - Not returning a list of data into index view in ASP.NET Core MVC 模型的ASP.NET Core MVC List属性在视图中为空 - ASP.NET Core MVC List property of model empty in view ASP.NET 核心 MVC - 将 Model 数据从视图传递回 Controller - ASP.NET Core MVC - Passing Model Data Back to Controller from View ASP.NET MVC Core TextBoxFor event pass model from View to Controller - ASP.NET MVC Core TextBoxFor event pass model from View to Controller 从控制器返回Json数据以查看ASP.NET MVC - Returning Json Data From Controller to View ASP.NET MVC 在ASP.NET MVC中从View传递模型到Controller - Passing Model to Controller from View in ASP.NET MVC 从 ASP.NET MVC 迁移到 ASP.NET 核心 MVC - 操作 model 绑定导致 Z37A6259CC6491DAE299A8D - Migration from ASP.NET MVC to ASP.NET Core MVC - action model binding resulting null 调用不是来自数据库的模型以列出 ASP.NET Core 5 MVC - Call a model not from database to list ASP.NET Core 5 MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM