最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ASP.NET MVC4 Refresh view after adding a comment - Stack Overflow

programmeradmin7浏览0评论

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 mented by logged users. Everything works fine (adding ment and viewing it), but to view newly added ment 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._ment)
</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 ment, string komentarz, int articleId)
    {
        if (komentarz != String.Empty)
        {
            if (ModelState.IsValid)
            {
                ment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
                ment.Content = komentarz;
                ment.ArticleId = articleId;
                db.Comments.Add(ment);
                db.SaveChanges();

            }

        }
        ArticleViewModel widok = new ArticleViewModel();
        widok._ment = (from b in db.Comments where b.ArticleId == articleId select b).ToList();
        return PartialView("_Comment", widok._ment);

    }

Article/Details GET method

public ActionResult Details(int id = 0)
    {
        ArticleViewModel widok = new ArticleViewModel();
        widok._ment = (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._ment);
        }
        if (widok == null)
        {
            return HttpNotFound();
        }
        return View(widok);
    }

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 mented by logged users. Everything works fine (adding ment and viewing it), but to view newly added ment 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._ment)
</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 ment, string komentarz, int articleId)
    {
        if (komentarz != String.Empty)
        {
            if (ModelState.IsValid)
            {
                ment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
                ment.Content = komentarz;
                ment.ArticleId = articleId;
                db.Comments.Add(ment);
                db.SaveChanges();

            }

        }
        ArticleViewModel widok = new ArticleViewModel();
        widok._ment = (from b in db.Comments where b.ArticleId == articleId select b).ToList();
        return PartialView("_Comment", widok._ment);

    }

Article/Details GET method

public ActionResult Details(int id = 0)
    {
        ArticleViewModel widok = new ArticleViewModel();
        widok._ment = (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._ment);
        }
        if (widok == null)
        {
            return HttpNotFound();
        }
        return View(widok);
    }
Share Improve this question edited Jan 6, 2014 at 11:00 user2962215 asked Dec 30, 2013 at 10:51 user2962215user2962215 557 bronze badges 2
  • Could you add your action code ? Create action in the Comment controller – Selman Genç Commented Dec 30, 2013 at 12:21
  • OK, added missing code ;) – user2962215 Commented Jan 5, 2014 at 11:28
Add a ment  | 

5 Answers 5

Reset to default 3

If you are to use Ajax.BeginFrom like you have shown. (but with some modifications)

using (Ajax.BeginForm(new AjaxOptions {
       HttpMethod= "get",
       InsertionMode=InsertionMode.Replace, 
       UpdateTargetId = "myDisplayID"
}))

, there are 3 things you need.

  1. your ment section should be in a partial view and strongly type it (for your solution it might be a list of ments)
  2. you should check if the request is ajax within the Action, using 'Request.IsAjaxRequest()'
  3. if it's an ajax request, then you should return a partial view not the view.

.

public ActionResult Details()
{   
    //what ever the data retrieve code you have
    return View(alldata);         
}

[HttpPost]
public ActionResult Create(Comment ment, string komentarz)
{
    if (komentarz != String.Empty)
    {
        if (ModelState.IsValid)
        {
            ment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
            ment.Content = komentarz;
            db.Comments.Add(ment);
            db.SaveChanges();
        }            
    }

    ArticleViewModel widok = new ArticleViewModel();
    widok._ment = (from b in db.Comments where b.ArticleId == id select b).ToList();
    return PartialView("_Comments",widok._ment);
}

submit ment - view

using (Ajax.BeginForm("Create", 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>
    }

in your view instead of

<h4>Comments</h4>
<table>
    // table with ments for this article
</table>

put

<div id="myDisplayID">
    @Html.Partial("_Comments", Model.Comments)
</div>

_Comments partial view

@model IEnumerable<Comments>
<h4>Comments</h4>
<table>
    // table with ments for this article
</table>

I think doing it this way will improve the user experience if you also happen to add new ments using ajax

You can refresh in javascript with window.location.href=window.location.href. Reload posts the data again.

Best option to do this send a post request with an ajax Call, like this:

 var ment = $("#txtComment).val(); // change this id with your textarea id
 var id = @Model._article.ArticleId;
 $.ajax({
            url: "/Comment/Create",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({ content: ment, articleId: id }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                // if you returning all your ment use this
                $("table").html(data.allContent);
                // or if you return just a row with this ment
                $("table").prepend(data.Comment);

           }

I assume your Action method like this:

[HttpPost]
public ActionResult Create(string content,int articleId)
{
   ...
   return Json(new { allContent = ments }); // just for example
}

Problem solved with changing

return View()

in POST Create Action to

ControllerContext.HttpContext.Response.Redirect(ControllerContext.HttpContext.Re​quest.Url.ToString());

without any Partial Views, AJAX and Jquery

Try this :

return RedirectToAction("Index", "Comments");

or however your controller is called. But..

The best solution for me is to add ment asynchronously with jquery ajax. Comment/Create should return html as response (partialview), and you should replace old table with new one.

$.ajax({

            url: "Comments/Create",
            data: {ment : "bla bla", articleId : 1},
            success: function (response) {

                if (response == 'True') {
                    $('table').html(response);

                }
            }
        });

Check some jquery ajax tutorials, it's very useful for such things. You can also use javascript when you are firing the action, which will prepare some html code with another row, and append it to table. Both of these ways are very nice, because you are not forced to reload the page.

发布评论

评论列表(0)

  1. 暂无评论