ASP.NET MVC3 ajax partial view refresh
I would use jquery ajax to call the action and then return the partial view from the controller. Then reload the returned html into the container using jquery.
First, add a refresh button or something you can trigger the ajax event... then do the below javascript.
Do something like this:
<div id="post_comments">
@{Html.RenderPartial("_RefreshComments", Model);}
</div>
<div id="commentForm">
@using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "post_comments"
}
))
{
// form content goes here
<p id="buttons">
<input type="submit" value="@Strings.Save" />
<input type="button" id="refreshButton" value="Refresh" />"
</p>
}
$('#refreshButton').click(function(){
$.ajax({
url: 'controller/Details.aspx',
datatype: 'html',
success: function(data) {
$('#post_comments').empty().html(data);
}
});
});
Obviously, the url needs to be the route to your action. Other than that, this should work fine for you.
TheKnyazz
Updated on June 04, 2022Comments
-
TheKnyazz almost 2 years
I am facing a problem with ajax updating of div in asp.net mvc3.
I have a View with content
<div id="post_comments"> @{Html.RenderPartial("_RefreshComments", Model);} </div> <div id="commentForm"> @using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "post_comments" } )) { // form content goes here <p id="buttons"> <input type="submit" value="@Strings.Save" /> </p> }
This is my partial view
@model Project.Models.Posts.PostDetailsViewModel @{ foreach (var c in Model.ApprovedComments) { @Html.DisplayFor(x => c) } }
I have a controller
public ActionResult Details(int id, FormCollection form ) { var model = new PostDetailsViewModel(UnitOfWork, id); return PartialView("_RefreshComments", model); }
I have following script included in my layout cshtml
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
and also
<appSettings> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>
It really works, I am able to add comments, but controller only returns the PartialView, not contained in the layout. I am found ASP.net MVC3 - Razor Views and PartialViews with Ajax Postbacks but nothing from there helped me.
Does anyone have any ideas?
-
TheKnyazz almost 12 yearsIt almost works, but I am facing some problems with passing params through the @Url.Action(). I need to pass formcollection and Id.