Question

I'm using the Microsoft unobtrusive AJAX in a basic MVC5 project.

If I have a div:

Index.cshtml

<div class="panel-group" id="mainContent">
</div>

and I have this partial view:

PanelPartial.cshtml

    <div class="panel panel-default">
        <div class="panel-body">
            <p>Hello world!</p>
        </div>
    </div>

I know that I can get it to display once by using

@Ajax.ActionLink("Change content", "UpdateContent","Home", new AjaxOptions {UpdateTargetId = "mainContent"})

Which calls this controller:

HomeController.cs

public ActionResult UpdateContent()
    {
        return PartialView("PanelPartial");
    }

and replaces the div content with the partial view.

The AJAX option InsertionMode = InsertionMode.After is close to what I want since that inserts the partial after the div, instead of replacing it. That would mean that I could use that multiple times to add as many partials as I want, outside of the target div. But how can I do it inside the target div?

Was it helpful?

Solution

You'll probably have to write your own Javascript function to handle this situation and tell your AjaxOptions to call this function in the OnSuccess event.

using (Ajax.BeginForm("Change content",
    "UpdateContent",
    "Home",
    new AjaxOptions()
    {
        OnSuccess = "updateMainContent"
    }))
{
    <!-- ...HTML... -->
}

Javascript (using jQuery):

// The data parameter will be whats returned from your controller action.
// In this case it will be the resulting HTML from your partial view.
function updateMainContent(data) {
    $("#mainContent").append(data);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top