如何为asp-for标签分配实体类的嵌套属性以进行模型验证?

问题描述 投票:0回答:1

我有一个像这样的实体类:

public class User : BaseEntity
    {
       
        public long id { get; set; }

        [Required(ErrorMessage ="It is a mandatory field.")]
        public string fullname { get; set; }

    }

还有一个 DTO 类: [注意有一个**用户列表**]

public class ResultGetUsersDto
    {
        public List<GetUsersDto> Users { get; set; }
        public int Rows { get; set; }
    }

然后,我有一个剃刀页面,其中用户的信息将通过模式进行更改: 标题:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using alefbafilms.application.Services.Users.Queries.GetUsers
@model ResultGetUsersDto;

身体:

<!-- Modal -->
    <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">

            <form id="formdata" asp-action="UpdateUser" method="post">

            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">UPDATE USERS</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="txtEditIdUser" />
                    <input name="" asp-for="" type="text" class="form-control" id="txtEditFullname" />
   <button type="button" onclick="UpdateUser()" class="btn btn-primary waves-effect waves-light">Save</button>
                </div>

            </div><!-- /.modal-content -->

            </form>

        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

问题是,我无法访问 List 类的嵌套属性。 我的意思是“用户”和“全名”属性。 我如何访问它以设置为“asp-for”以进行模型验证?

我尝试发现 ResultGetUsersDto 类的嵌套属性,例如:

  1. asp-for="Users.fullname"
  2. asp-for=“全名”
  3. asp-for="用户[0].全名"
  4. ... 但我失败了。
asp.net-mvc dto model-validation
1个回答
0
投票

我刚刚找到答案了! 事实上,对此有一个简单而可笑的答案。 答案是,它与我们有多少 DTO(请求或响应类型)无关!我们必须设置与 DTO 验证相同的用户验证。 因此,我们将有:

    public class GetUsersDto
{
   public long id { get; set; }

    [Required(ErrorMessage ="It is a mandatory field.")]
    public string fullname { get; set; }
}

关于使用这个: 标题:(相同的代码):

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@使用 alefbafilms.application.Services.Users.Queries.GetUsers @model ResultGetUsersDto;

身体:

                        <input asp-for="Users[0].fullname"
                       type="text"
                       class="form-control"
                       id="txtEditFullname" />
                    <span asp-validation-for="Users[0].fullname"
                      class="text-danger"
                      data-valmsg-for="Users[0].fullname">
                    </span>

我们必须使用第一个索引(零索引)作为实体的样本。

© www.soinside.com 2019 - 2024. All rights reserved.