MVC 4 Updating a partial view from another partial view using Ajax.BeginForm() - ajax

I have a comment section set up on one of my pages. The parent view has a partial view which shows the comments for that ID and gives the option to display another partial view to post a comment. When someone post a comment I want the first partial view within the parent to refresh displaying the new comment.
Currently when you click Post Comment, the AddComment method is called and added to the database. I get an error saying that I am passing the wrong type of model to the view. It seems to be trying to pass the return value to my AddComment partial view instead of injecting it into Partent View Div.
Parent View
#model QIEducationWebApp.Models.Course
#{
ViewBag.Title = "Course Details";
}
<h1 class="page-header">#ViewBag.Title</h1>
Javascript is here
.
.
.
<table class="table">
DETAILS HERE
</table>
<ul id="view-options">
<li>#Html.ActionLink("Back to Courses", "Index", "Course")</li>
</ul>
<input type="button" id="View" class="ShowComment" value="Show Comments"/>
<div id="CommentSection"/>
Partial View to view comments
Javascript is here
.
.
.
<div class="CommentSection">
#foreach (var item in Model)
{
<div class="Comment">
<div class="CommentText">
#Html.DisplayFor(modelItem => item.CommentText)
</div>
<div class="CommentSep">
<span class="Commenter">#Html.DisplayFor(modelItem => item.UserName)</span> - <span class="CommentDate">#Html.DisplayFor(modelItem => item.CommentDate)</span>
</div>
</div>
}
<input type="button" id="Post" class="AddComment" value="Add a Comment"/>
<br />
<br />
</div>
<div id="AddComment" />
<br />
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewComments",
new { courseID = #ViewBag.courseID, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new PagedListRenderOptions { MaximumPageNumbersToDisplay = 5, DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded },
new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "CommentSection" }))
Method behind the is partial view
public PartialViewResult ViewComments(int courseID, int? page = 1)
{
ViewBag.courseID = courseID;
var coursecomments = db.CourseComments.Where(cc => cc.CourseID == courseID);
int pageSize = 10;
int pageNumber = (page ?? 1);
return PartialView(coursecomments.OrderByDescending(cc => cc.CommentDate).ToPagedList(pageNumber, pageSize));
}
Partial to Post Comment
Javascript is here
.
.
.
#using (Ajax.BeginForm("AddComment", "CourseComment", new { courseID = #ViewBag.courseID, userName = #User.Identity.Name },
new AjaxOptions { UpdateTargetId = "CommentSection" }))
{
#Html.ValidationSummary(true)
<div class="NewComment">
<div class="editor-field">
#Html.TextAreaFor(model => model.CommentText, new { maxLength = 500 })
#Html.ValidationMessageFor(model => model.CommentText)
</div>
<input type="submit" class="PostComment" value="Post Comment" />
<div id="Counter" class="CommentCounter"/>
</div>
}
Controller method linked to the Post Comment Ajax.BeginForm()
public PartialViewResult AddComment(CourseComment coursecomment, int courseID, String userName)
{
coursecomment.CommentDate = System.DateTime.Now;
coursecomment.CourseID = courseID;
coursecomment.UserName = userName;
if (ModelState.IsValid)
{
db.CourseComments.AddObject(coursecomment);
db.SaveChanges();
}
ViewBag.courseID = courseID;
return ViewComments(courseID);
}
Adding pictures
Details
After selecting View Comments button
After selecting Add Comment
After Posting the the comment I want the list of Comments to refresh displaying the newly added Comment. Like So

For now I have it changed. I wanted to the comments section to be hidden until the show comments was clicked. Then after posting a comment on the comments section was refreshed, but I couldn't get that to work. So just reloading the whole page will refresh the comments section, but make it hidden at that time. I made it so that the comments section shows by default without the option to hide it. So unless anyone can figure out a way to get it to work how I wanted, this works for now.

Related

Saving multiple partial views from one main page

Here is my requirement :
I am designing a page to add a vehicle to the database :
Normal vehicle information [Model - Inventory]
Some other features [Model - IList]
Here is my index.cshtml page
#model Model.ViewModel.VehicleViewModel
<div>
<div class='col-md-12'>
<div class="form-group">
<input id="mainFormSubmit" type="button" value="Save" class="btn btn-default" />
</div>
</div>
#{Html.RenderPartial("~/Views/Shared/_InventoryPartial.cshtml", Model.InventoryVM);}
#{Html.RenderPartial("~/Views/Shared/_StandardFeaturePartial.cshtml", Model.StandardFeatures);}
</div>
<script type="text/javascript">
$('#mainFormSubmit').click(function () {
$('#InventoryForm').submit();
$("#StandardFeatureForm").submit();
});
</script>
This is my view model class
public class VehicleViewModel
{
public InventoryViewModel InventoryVM { get; set; }
public IList<StandardFeature> StandardFeatures { get; set; }
}
The Inventory partial view [_InventoryPartial.cshtml]
#model Model.ViewModel.InventoryViewModel
#{
var options = new AjaxOptions() { HttpMethod = "Post" };
}
<div class="container">
<div class="row">
<div class="col-md-12">
#using (Ajax.BeginForm("InventorySave", "AddVehicle", options, new { id = "InventoryForm" }))
{
<fieldset>
<legend>Inventory Info</legend>
<div class='col-md-6'>
<!-- VIN input-->
<div class="form-group">
#Html.LabelFor(x => x.VIN, new { #class = "col-md-4 control-label" })
<div class="col-md-7">
#Html.TextBoxFor(x => x.VIN, new { #class = "form-control", #placeholder = "VIN" })
</div>
</div>
</div>
</fieldset>
}
The standard feature partial view [_StandardFeaturePartial.cshtml]
==
#model IEnumerable<Model.DomainModel.StandardFeature>
#{
var options = new AjaxOptions() { HttpMethod = "Post" };
}
<div class="container">
<div class="row">
<div class="col-md-12">
#using (Ajax.BeginForm("StandardFeatureSave", "AddVehicle", options, new { id = "StandardFeatureForm" }))
{
When I am clicking on index page SAVE button, only
$('#InventoryForm').submit();
$("#StandardFeatureForm").submit();
last one(StandardFeatureForm) is executing.
Please let me know if this process is correct, and what could be the reason of this issue.
You should not call the submit method twice. Depending of the browser you can face different issues :
the form submission causes the browser to navigate to the form action and the submission
of the first may prevent the submission of the second
The browser could detected there are two requests and discards the
first submit.
In your case it will be easier to wrap your two partial views inside a unique form.
#using (Ajax.BeginForm("InventorySave", "AddVehicle", FormMethod.Post, new { id = "InventoryForm" }))
{
#{Html.RenderPartial("~/Views/Shared/_InventoryPartial.cshtml", Model.InventoryVM);}
#{Html.RenderPartial("~/Views/Shared/_StandardFeaturePartial.cshtml", Model.StandardFeatures);}
}
However when the partial views render they are not generating the correct name attributes for the larger modelModel.ViewModel.VehicleViewModel you want to use :
public void InventorySave(VehicleViewModel vehicleViewModel) {}
In this case you should use EditorTempmlate instead of partial views. It's simple to do from your partial views and this post should help you :Post a form with multiple partial views
Basically, drag your partials to the folder ~/Shared/EditorTemplates/
and rename them to match the model name they are the editor templates
for.
Finally something like :
#model Model.ViewModel.VehicleViewModel
#using (Html.BeginForm("InventorySave", "AddVehicle", FormMethod.Post, new { id = "InventoryForm" }))
{
#Html.EditorFor(m => m.InventoryVM);
#Html.EditorFor(m => m.StandardFeatures});
}
The Ajax.BeginForm helper already has a submit event associated to it which creates an Ajax POST request. When you are manually submitting your form using $('#InventoryForm').submit();, you're calling both and the submit events which can have strange side effects.
There are a few ways around this. Here is one solution
Change your forms to a regular HTML form using the Html.BeingForm helper.
Amend your script to create ajax requests and use the form data
$('#InventoryForm').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(r) {
//Do something
});
});
$('#StandardFeatureForm').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(r) {
//Do something
});
});
Hope this helps

Client side paging for Asp.Net MVC3

this is my MVC action that returns a list of posts:
public ActionResult Posts()
{
var blogPost = _blogRepository.GetAllPost();
var blogPostViewModel = blogPost.ConvertToPostViewModelList();
return View("Posts", blogPostViewModel);
}
and also this is my View
#model IEnumerable<Blog.Web.UI.ViewModels.PostViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#foreach (var item in Model)
{
<div>
<h3>
#Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.Id, postSlug = item.UrlSlug }, null)
</h3>
</div>
<div>
<span>Category: </span>#item.Category.Name
</div>
<div>
<span>Tag: </span>#item.Tag.Name
</div>
<div>
#item.CreationDate.ToLongDateString()
</div>
<div>
#Html.DisplayTextFor(p => item.Body)
</div>
}
</div>
I want to implement a Client Side paging for this page that render all of the post by date , is it possible ?? or I should change my code to make it server side ??
http://haacked.com/archive/2009/04/13/using-jquery-grid-with-asp.net-mvc.aspx
It's old but relevant and should help you achieve what your looking for.

Ajax not working with MvcPaging

Currently I am using the MvcPaging nuget package that I retrieved from here: https://github.com/martijnboland/MvcPaging
My problem is that instead of replacing my element when I use the #Html.Pager helper. It opens up the partialview in a new tab.
My goal is to have my QuickLinks section update via Ajax without a full page refresh.
This is my controller:
private CasuallyProDb db = new CasuallyProDb();
private const int DefaultPageSize = 7;
//
// GET: /Home/
public ActionResult Index()
{
int currentPageIndex = 0;
var news = db.PostedNews.OrderBy(a=>a.NewsId).ToPagedList(currentPageIndex, DefaultPageSize);
return View(news);
}
public ActionResult AjaxPage(int? page)
{
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
var news = db.PostedNews.OrderBy(a => a.NewsId).ToPagedList(currentPageIndex, DefaultPageSize);
return PartialView("_QuickLinks", news);
}
This is my index view that renders the partial view:
#model IPagedList<CasuallyPro.Models.News>
#using MvcPaging
<div id="quickLinksWrapper" class="float-right">
#Html.Partial("_QuickLinks", Model)
</div>
And this is my _QuickLinks.cshtml partial view:
#model IPagedList<CasuallyPro.Models.News>
#using MvcPaging
<div id="quickLinksDisplay">
<ul>
#foreach (var news in Model)
{
<li>
<img alt="" src="#Html.DisplayFor(modelItem => news.CategoryIcon)"/>
<div class="quickLinksTitle">#Html.DisplayFor(modelItem => news.Title)<br/>
<span class="quickLinksDetails">
<span class="quickLinksUsername"> Posted by #Html.DisplayFor(modelItem => news.PostedUserName)</span>
<span class="quickLinksDate"> on #Html.DisplayFor(modelItem => news.PostedDate)</span>
</span>
</div>
</li>
}
</ul>
<div id="quickLinksPagedList">
#Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, new AjaxOptions
{
UpdateTargetId = "quickLinksWrapper"
}).Options(o => o.Action("AjaxPage"))
</div>
I am looking at the sample project they provided and it looks like this should do it but unfortunately it just isn't working appropriately. I have the script referenced in the head section of my _Layout.cshtml for unobtrusive ajax:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Any guidance would be appreciated.

MVC3 Ajax ChildAction

I am having a difficult time figuring out how to get AJAX working with child actions in MVC3. I have a View that contains a section rendered by a child action. That child action renders a partial view which has a paged list on it. I need to make it so that when a user clicks on another page number on the page list pager only the bottem part of the view containing a list of videos will be updated. I have included my code and would really appreciate some help as I am still confused on some of the ways MVC3 works with AJAX. Thanks in advance.
My View:
#model UltimateGameDB.Domain.Entities.Video
#{
ViewBag.Title = "Video Home";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using PagedList
#using PagedList.Mvc
#section MainBanner {
<section id="videos-featured">
#Html.Partial("_Video", Model)
<div id="videos-featured-detail">
#Html.Partial("_VideoDetail", Model)
#Html.Action("MiniFeaturedVideo", "Video")
</div>
</section>
}
#Html.Action("RecentVideos", "Video", new { page = ViewBag.page })
My Controller Methods:
public ActionResult VideoHome(Guid? selectedVideoId, int? page)
{
var pageIndex = page ?? 1;
ViewBag.page = pageIndex;
if (selectedVideoId == null)
{
selectedVideoId = ugdb.Videos.Where(v => v.IsFeatured == true).OrderBy(v => v.Timestamp).FirstOrDefault().VideoID;
ViewBag.Autoplay = 0;
}
else
{
ViewBag.Autoplay = 1;
}
return View(ugdb.Videos.Find(selectedVideoId));
}
[ChildActionOnly]
public ActionResult RecentVideos(int? page)
{
IQueryable<Video> videoList = ugdb.Videos.OrderBy(v => v.Timestamp);
var pageIndex = page ?? 1;
var onePageOfVideos = videoList.ToPagedList(pageIndex, 8);
ViewBag.OnePageOfVideos = onePageOfVideos;
return PartialView("_RecentVideos");
}
My Partial View:
#using PagedList
#using PagedList.Mvc
<div id="main-content" class="videos">
<section>
<a class="body-title"><span>RECENT VIDEOS</span><span class="title-arrow"></span></a>
<div class="main-hr"></div>
#foreach (var video in ViewBag.OnePageOfVideos)
{
<a class="video-entry" href="#Url.Action("VideoHome", "Video", new { selectedVideoId = video.VideoID })">
<img src="http://img.youtube.com/vi/#video.YouTubeID/default.jpg" alt="#video.VideoName" />
<div class="video-details">
<h2>#video.VideoName</h2>
<p>#video.VideoType</p>
</div>
</a>
}
</section>
<div class="pagination">
#Html.PagedListPager((IPagedList)ViewBag.OnePageOfVideos, page => Url.Action("VideoHome", "Video", new { page = page }), PagedListRenderOptions.OnlyShowFivePagesAtATime)
</div>
</div>
What you're probably gonna want to do is insert an AjaxForm after the main-content div and end it before the main-content div closes.
Then the PagedListPager can submit to a Json Method in your controller which will return the content (e.g. list of videos) for the Ajax form to update.

How i can submit multiple objects inside the form post values to be added

i have a create view to add answers to a question, currently the user can only add one answer at the same time when he clicks on the submit button, instead of this i want the user to be able to insert multiple answers objects into the same view and then the system to add all these new answer objects to the database after the user click on the submit button, my current view looks as the follow:-
#model Elearning.Models.Answer
#{
ViewBag.Title = "Create";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id = "remove">
#using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "remove"
}))
{
<div id = "returnedquestion">
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
<input type= "hidden" name = "questionid" value = #ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = #ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
and the action methods look as the follow:-
public ActionResult Create(int questionid)//, int assessmentid)
{
ViewBag.questionid = questionid;
Answer answer = new Answer();
return PartialView("_answer",answer);
}
//
// POST: /Answer/Create
[HttpPost]
public ActionResult Create(int questionid, Answer a)
{
if (ModelState.IsValid)
{
repository.AddAnswer(a);
repository.Save();
return PartialView("_details",a);
}
return View(a);}
so how i can modify the above code to be able to insert multiple answer objects at the same view and then submit these answers objects at the same time when the user click on the submit button?
Try Post a List
Add input by javascript when user click "Add Answer".
And when submit the form ,it will post all answer data to binding to List
<script>
$(document).ready(function () {
var anwserCount = 1;
$("#addbutton").click(function () {
$("#AnwsersDiv")
.append("<input type='text' name='Anwsers[" + anwserCount + "]'/>");
anwserCount += 1;
});
});
</script>
#using (Html.BeginForm())
{
<div id="AnwsersDiv">
<input type="text" name="Anwsers[0]" />
</div>
<input id="addbutton" type="button" value="Add answer" />
<input type="submit" value="submit" />
}
Model
public class Answer
{
public List<String> Anwsers { get; set; }
}
When submit the form
I think this is what you are looking for
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Conclusion: you should make the post action with ICollection<Answer> Parameter, then it will be easy to get them when you post your main form, and create the appropriate QUESTION object, then save them all with only one submit.

Resources