【问题标题】:TryValidateModel returning false despite a valid model尽管模型有效,但 TryValidateModel 返回 false
【发布时间】:2021-03-01 20:30:34
【问题描述】:

我有一个控制器,它使用模型绑定从表单中检索数据。我需要在验证之前对模型进行一些编辑,所以我按照文档的建议使用 TryValidateModel。但是由于某种原因,即使“用户”不为空,“作者”总是无效的。真的很困惑这里发生了什么,非常感谢任何帮助。

调试器显示有效模型:

控制器:

    [Authorize]
    [HttpPost]
    public async Task<IActionResult> Create([Bind("Id, Title, Content")] Post post)
    {
        var user = await userManager.GetUserAsync(User);
        post.Author = user;
        post.UpvotedBy.Add(user);

        if (post.Title != null && post.Content != null)
        {
            post.Title = post.Title.Trim();
            post.Content = post.Content.Trim();
        }

        if (TryValidateModel(post))  // Never true
        {
            context.Add(post);
            context.SaveChanges();

            return RedirectToAction("Details", new { id = post.Id });
        }
        else return View(post);
    }

型号:

public abstract class Entry
    {
        public Entry()
        {
            DateCreated = DateTime.Now;
            Upvotes = 1;
            Downvotes = 0;
            VoteScore = 1;

            Replies = new List<Comment>();
            SavedBy = new List<ApplicationUser>();
            HiddenBy = new List<ApplicationUser>();
            UpvotedBy = new List<ApplicationUser>();
            DownvotedBy = new List<ApplicationUser>();
        }

        public int Id { get; set; }

        [Required, StringLength(40000)]
        public string Content { get; set; }

        [Required, DataType(DataType.DateTime)]
        public DateTime DateCreated { get; set; }

        [Required]
        public int Upvotes { get; set; }
        [Required]
        public int Downvotes { get; set; }
        [Required]
        public int VoteScore { get; set; }

        [Required]
        public ApplicationUser Author { get; set; }
        [Required]
        public ICollection<Comment> Replies { get; set; }
        [Required]
        public ICollection<ApplicationUser> SavedBy { get; set; }
        [Required]
        public ICollection<ApplicationUser> HiddenBy { get; set; }
        [Required]
        public ICollection<ApplicationUser> UpvotedBy { get; set; }
        [Required]
        public ICollection<ApplicationUser> DownvotedBy { get; set; }
    }

    public class Post : Entry
    {
        [Required, StringLength(300, MinimumLength = 1)]
        public string Title { get; set; }
    }

表格:

@model Post
@{
    ViewData["Title"] = "New post";
}

<div class="container">
    <form asp-action="Create">
        <div class="form-group mb-3">
            <h3>Title</h3>
            <input asp-for="Title" class="form-control bg-dark text-white border-secondary" 
                   placeholder="Make it descriptive!"/>
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
        <div class="form-group mb-3">
            <h3>Content</h3>
            <textarea asp-for="Content" class="form-control bg-dark text-white border-secondary" 
                      placeholder="What do you have to say?" rows="5"></textarea>
            <span asp-validation-for="Content" class="text-danger"></span>
        </div>

        <a href="javascript:history.go(-1)" class="btn btn-outline-danger" role="button">
            <i class="fas fa-ban me-1"></i> Cancel
        </a>
        <button type="submit" class="btn btn-outline-primary">
            <i class="fas fa-save me-1"></i> Submit
        </button>
    </form>
</div>

【问题讨论】:

  • 您检查过ModelState.Values 是否有错误?
  • “作者”总是无效,我会更新帖子

标签: c# .net asp.net-mvc .net-core asp.net-core-mvc


【解决方案1】:

在调用TryValidate之前尝试清除ModelState

// your model update code
ModelState.Clear();
if (TryValidateModel(post))
{
    ....
}

另一种选择是在验证发生之前实现custom model binder 以通过UserManager 绑定Author

【讨论】:

  • 这已解决,谢谢!但为什么有必要这样做呢?
  • @chmorgan TryValidateModel 没有清除已经存在的错误,可能是由于一些嵌套/递归调用,如果应该从TryValidateModel 调用中预期这种副作用,还有待商榷。
  • 你救了我的命,哈哈,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
相关资源
最近更新 更多