[英]Empty razor page, check if article number exists in cmment
所以我有一个评论可以更新的 crud,我已经想出了如何在评论不存在时显示一条消息,但是当我放置一个不存在的文章编号时它会崩溃(文章编号不能为空)
剃刀页面背后的代码:
public class UpdateCommentModel : PageModel
{
[BindProperty]
public CommentClass comment { get; set; }
[BindProperty]
public int articleNumber { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
UserManager findUser = new UserManager();
comment.user = findUser.FindUser(Convert.ToInt32(HttpContext.Session.GetString("username")));
NewsArticleManager FindArticleNumber = new NewsArticleManager();
comment.article = FindArticleNumber.FindNewsArticle(articleNumber);
CommentManager updateToCommentDatabase = new CommentManager();
bool succeeded = updateToCommentDatabase.UpdateComment(comment);
if (succeeded)
{
string message = "The tip article has been deleted!";
ViewData["Message"] = message;
}
else
{
string message = "This article does not exist";
ViewData["Message"] = message;
}
return Page();
}
else
{
ViewData["Message"] = "Please enter all data fields";
return Page();
}
}
数据库代码:
public bool UpdateDb(CommentClass comment)
{
using (MySqlConnection connection = new MySqlConnection(databaseConnection))
{
//SQL command to insert the news article into the database
string sql = "UPDATE comment SET CommentId = @CommentId, ArticleId = @ArticleId, UserId = @UserId, CommentText = @CommentText WHERE CommentId = @CommentId AND ArticleId = ArticleId";
MySqlCommand command = new MySqlCommand(sql, connection);
command.Parameters.AddWithValue("@CommentId", comment.CommentId);
command.Parameters.AddWithValue("@ArticleId", comment.article.ArticleNumber);
command.Parameters.AddWithValue("@UserId", comment.user.UserId);
command.Parameters.AddWithValue("@CommentText", comment.CommentText);
connection.Open();
int amount = command.ExecuteNonQuery();
return amount > 0;
}
}
管理员代码:
//Delete article
public bool DeleteComment(int commentId)
{
FillCommentList();
return commentDB.DeleteDb(commentId);
}
有人知道如何解决这个问题吗?
在不知道您的标记是什么样子的情况下,我建议:
if (articleNumber == 0)
{
ModelState.AddError("articleNumber", "Article Number should be greater than zero");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.