【发布时间】: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