MVC 4 - Ajax - Replace one partial one view with another

James P picture James P · Apr 18, 2013 · Viewed 9.4k times · Source

I'm trying to replace the contents of a div in a Main view with partial views depending on which @Ajax.ActionLink is clicked.

Initally I load the _CaseLoad partial view then I would like to be able to switch between the two partial views _CaseLoad and _Vacancies when I click on the relevant ActionLink. I have bothe partial views and the Index view in the 'Main' folder.

When I click on the 'Vacancies' link it briefly shows the LoadingElementID but it does not replace the _CaseLoad partial view with _Vacancies partial view?

Controller Action (MainController):

    public ActionResult Index(int page = 1, string searchTerm = null)
    {
        MainIndexViewModel model = new MainIndexViewModel()
        // Populate Model

        return View(model);

    }

Main Index View:

@model Project.WebUI.Models.MainIndexViewModel

@{
  ViewBag.Title = "Index";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<div id="MainIndex">
        <div id="Menu">

            @Ajax.ActionLink("CaseLoad", "_CaseLoad", "Main", null, new AjaxOptions() { UpdateTargetId = "Main", InsertionMode = InsertionMode.Replace, HttpMethod = "GET",
                LoadingElementId = "busycycle" }) |

            @Ajax.ActionLink("Vacancies", "_Vacancies", "Main", null, new AjaxOptions() { UpdateTargetId = "Main", InsertionMode = InsertionMode.Replace, HttpMethod = "GET",
                LoadingElementId = "busycycle" })

        </div><hr/>


        <div id="busycycle" style="display:none;"><img src="~/Content/images/preloader-w8-cycle-black.gif" /></div>
        <div id="Main">
            @Html.Partial("_CaseLoad")
        </div>

    </div>

Answer

ararog picture ararog · Apr 18, 2013

Your call to @Ajax.ActionLink is wrong, you are doing this:

@Ajax.ActionLink("CaseLoad", "_CaseLoad", "Main", null, new AjaxOptions() { UpdateTargetId = "Main", InsertionMode = InsertionMode.Replace, HttpMethod = "GET",
            LoadingElementId = "busycycle" })

Which means your link text is "CaseLoad", and the action to be called in "MainController" is "_CaseLoad"? Isn't "_CaseLoad" the name of your partial view?

To fix this, you must create CaseLoad and a Vacancies actions in your MainController, make both methods return PartialView("_CaseLoad.cshtml", model); or PartialView("_Vacancies.cshtml, model) like below:

public ActionResult CaseLoad(int page = 1, string searchTerm = null)
{
    MainIndexViewModel model = new MainIndexViewModel()
    // Poopulate Model

    return PartialView("_CaseLoad.cshtml", model);
}

I just cut off all implementation details just to get you an idea about how to fix the issue.