I am writing ASP.NET web application. I am using views generated by Visual Studio (Create/Delete/Details/Edit/Index). In my application I have Articles which can be commented by logged users. Everything works fine (adding comment and viewing it), but to view newly added comment I have to manually refresh page.
Structure of Article/Details View looks like:
@if (Request.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comment", new { articleId = Model._article.ArticleId }, new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDisplayID"
}))
{
@Html.ValidationSummary(true)
<fieldset>
<h4>Dodaj komentarz</h4>
<p>
@Html.TextArea("komentarz", new { @class = "form-control" })
</p>
<p>
<input type="submit" value="Dodaj" class="btn btn-primary btn-large" />
</p>
</fieldset>
}
}
else
{
<p>
<a href="~/Account/Login">Zaloguj się</a> aby dodać komentarz.
</p>
}
<hr />
<div id="myDisplayID">
@Html.Partial("_Comment", Model._comment)
</div>
EDIT Comment/Create GET method
public ActionResult Create(int articleId)
{
var komentarz = new Comment();
komentarz.ArticleId = articleId;
return View(komentarz);
}
Comment/Create POST
[HttpPost]
public ActionResult Create(Comment comment, string komentarz, int articleId)
{
if (komentarz != String.Empty)
{
if (ModelState.IsValid)
{
comment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
comment.Content = komentarz;
comment.ArticleId = articleId;
db.Comments.Add(comment);
db.SaveChanges();
}
}
ArticleViewModel widok = new ArticleViewModel();
widok._comment = (from b in db.Comments where b.ArticleId == articleId select b).ToList();
return PartialView("_Comment", widok._comment);
}
Article/Details GET method
public ActionResult Details(int id = 0)
{
ArticleViewModel widok = new ArticleViewModel();
widok._comment = (from b in db.Comments where b.ArticleId == id select b).ToList();
widok._article = (from t in db.Articles where t.ArticleId == id select t).FirstOrDefault();
if (Request.IsAjaxRequest())
{
return PartialView("_Comment", widok._comment);
}
if (widok == null)
{
return HttpNotFound();
}
return View(widok);
}