Rob Rob - 3 months ago 12
Ajax Question

Why is the partial view called by my action from ajax.beginform not appearing on the page?

I have a page which has a viewmodel, on the page the clicking of a button is submitting an ajax form:

@using (Ajax.BeginForm("finalstatus", "User", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "popupappear()",

}, new { id = "progForm"}))
{
@Html.HiddenFor(Model => Model.SectionID)
@Html.HiddenFor(Model => Model.CourseID)
}


This uses the controller action:

[HttpPost]
public ActionResult finalstatus(SubSectionViewModel model)
{

string currentuser = User.Identity.GetUserId();

var viewModel = db.enrollment
.Where(i => i.UserID == currentuser)
.Where(i => i.course.CourseID == model.CourseID)

.Select(x => new CurrentProgressViewModel
{

ovpcnt = (int)Math.Round((double)(100 * x.progress.Sum(c => c.progress)) / x.course.course_sections.SelectMany(i => i.course_subsections).Sum(c => c.scenes)),

}).Single();


return PartialView("_endofsection", viewModel);

}


This should calculate the progress percentage for the user and return that percentage in a partial view "_endofsection" to the page. The partial view uses the CurrentProgressViewModel which is holding the percentage.

Everything seems to work, however the partial view seems to not be loaded on the page, I can see it is being accessed and previews correctly in the network tab of google chrome. However it does not appear on the page where the form is, which is where I would expect the partialview to load.

What am I missing here? Why is this not appearing?

Additionally the onsuccess function that is called when the form submits successfully appears to only be called on the second click, however this is a secondary issue.

Answer

You are making an ajax call using Ajax.BeginForm helper method. So you need to specify where the response (of the ajax call) to be replaced in the DOM. You can specify that using the UpdateTargetId property. It should be the Id of the element to which you want to add the response coming back from your ajax call.

Also you need to a submit button to submit your form.

This should work assuming your action method is properly returning the partial view result without any errors.

<div id="YourDivToShowResult"></div>

@using (Ajax.BeginForm("finalstatus", "User", null, new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "popupappear()",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "YourDivToShowResult"

}, new { id = "progForm" }))
{
    @Html.HiddenFor(Model => Model.SectionID)
    @Html.HiddenFor(Model => Model.CourseID)

    <input type="submit"/>
}
Comments