问题描述:

  • Visual Studio Professional 2013
  • C# ASP.NET MVC 5 Web Application

Hey,

I am learning about MVC at the moment. What I am working on is simulating a blog. On this blog there is a comment section and when a user fills the forms and hits submit the code that runs leads to the comment being saved 3 times into the database. If another comment is submitted after that, it will be added 6 times. It is the following code that runs:

[ValidateAntiForgeryToken()]

public PartialViewResult _Submit(Comment comment) {

ViewBag.ArticleID = comment.ArticleID;

if (ModelState.IsValid) {

Exception ex = commentRepository.SaveComment(comment);

if (ex == null) {

TempData["Message"] = "Saving was succesful";

}

else {

TempData["Message"] = "An error occured. Further information: " + ex.Message;

}

}

else {

TempData["Message"] = "An error occured. Data may be not valid.";

}

List<Comment> comments = commentRepository.GetComments(comment.ArticleID);

return PartialView("_GetComment", comments);

}

Examining that with the debugger only let me know that there are new threads being created constantly. Replacing the code with a simpler version solves the problem e.g.:

commentRepository.SaveComment(comment);

List<Comment> comments = commentRepository.GetComments(comment.ArticleID);

ViewBag.ArticleID = comment.ArticleID;

return PartialView("_GetComment", comments);

EDIT:

Here are the GET and SAVE methods inside the comment-repository:

BlogContext context = new BlogContext();

public List<Comment> GetComments(int articleID) {

return context.Comments.Where(p => p.ArticleID == articleID).ToList();

}

//The error still occurs even if I always return null.

public Exception SaveComment(Comment comment) {

try {

context.Comments.Add(comment);

context.SaveChanges();

return null;

}

catch (Exception ex) {

return ex;

}

}

I just want to know what makes the code behave the way it does.

网友答案:

You're doing a few things incorrectly in your code which may be leading to your problems.

  • Because you're not doing any redirects in your controller method you should be using ViewData or ViewBag rather than TempData. TempData should only be used to preserve information when redirecting to a different controller action.
  • You are using exceptions as a return value rather than throwing them.

Here is your code rewritten to solve those issues. Whether it solves your original problem I'm not sure as I didn't try running it because I don't have your database and context object. Notice that SaveComment doesn't use a try/catch because it doesn't need one, any exception that occurs will just "bubble up" to the calling routine where it will be caught and acted upon.

You'll also need to change your view to reference ViewBag.Message rather than TempData["Message"].

BlogContext context = new BlogContext();

public List<Comment> GetComments(int articleID) {
    return context.Comments.Where(p => p.ArticleID == articleID).ToList();
}

public void SaveComment(Comment comment) {
    context.Comments.Add(comment);
    context.SaveChanges();
}

[ValidateAntiForgeryToken()]
public PartialViewResult _Submit(Comment comment) {  
    ViewBag.ArticleID = comment.ArticleID;
    if (ModelState.IsValid) {
        try {
            commentRepository.SaveComment(comment);
            ViewBag.Message = "Saving was succesful";
        }
        catch( Exception ex ) {
            ViewBag.Message = "An error occurred. Further information: " + ex.Message;
        }
    else {
        ViewBag.Message = "An error occurred. Data may be not valid.";
    }

    List<Comment> comments = commentRepository.GetComments(comment.ArticleID);
    return PartialView("_GetComment", comments);
}
相关阅读:
Top