user415394
user415394

Reputation: 303

Load partial view into div

I'm trying to load a partial view into a div from a calling view, however the partial view loads into a new page. There isn't much code to it and I've tried various ways from other posts, but it still loads into a new page. So I think I might be missing something fundamental.

Controller

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
    return View();
}

public ActionResult Test()
{
    return PartialView("Test");
}

View

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

@using (Ajax.BeginForm("Test", "Home", new AjaxOptions { InsertionMode=InsertionMode.Replace, UpdateTargetId = "mydiv" }))
{    
    @Ajax.ActionLink("Save", "Test", "Home", new AjaxOptions{ });
}

<div id="mydiv">
    @Html.Partial("Test")
</div>

PartialView

<h1>Test</h1>

Upvotes: 12

Views: 38771

Answers (4)

QMaster
QMaster

Reputation: 3904

I think you should use <input type="submit" /> instead of @Ajax.Actionlink(...)

in MVC4 you can add bundle @Scripts.Render("~/bundles/jqueryval") just after @Scripts.Render("~/bundles/jquery") or add script reference in script section in page view as shown below:

@section scripts
    {
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

    }

Good Luck.

Upvotes: 1

RezaRa
RezaRa

Reputation: 121

Add this line to your page (master page or layout)

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

just after MicrosoftMvcAjax.js line.

Upvotes: 12

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Couple of remarks about your code:

  • Ajax.* helpers in ASP.NET MVC 3 RC2 no longer use MS AJAX which has been deprecated in favor of jQuery, so your script inclusions are wrong. You need to include jquery
  • You have an ajax form without a submit button and an ajax link inside this form. This makes no sense. Either use an ajax form or an ajax link.

So your code might look something among the lines:

<script src="@Url.Content("~/scripts/jquery-1.4.4.js")" type="text/javascript"></script>

@Ajax.ActionLink("Save", "Test", "Home", new AjaxOptions { 
    InsertionMode = InsertionMode.Replace, 
    UpdateTargetId = "mydiv"
})

<div id="mydiv">
    @Html.Partial("Test")
</div>

Upvotes: 23

RailRhoad
RailRhoad

Reputation: 2128

Your partial needs to be within the ajax form

Upvotes: 0

Related Questions