I'm trying to replace part of a page with a partial view in ASP.Net MVC 5 (Visual Studio 13) using the following:
Views/Book/Index.cshtml:
<div id="bargainBook">
@Ajax.ActionLink("Click here for the Bargain Book!",
"BargainBook",
new AjaxOptions
{
UpdateTargetId = "bargainBook",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
</div>
In BookController:
public ActionResult BargainBook()
{
var book = GetBargainBook();
return PartialView("_BargainBook", book);
}
private Book GetBargainBook()
{
return db.Books
.OrderBy(b => b.Price)
.First();
}
In _BargainBook.cshtml:
@model BookDemo.Models.Book
<div>
<p>
<strong>Book</strong>
@Model.Name
</p>
<p>
<strong>Price</strong>
@String.Format("{0:F}", @Model.Price)
</p>
</div>
When I click on the link, I go to a full page view of the partial page data.
To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.
In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
Partial views shouldn't be used to maintain common layout elements. Common layout elements should be specified in _Layout. cshtml files. Don't use a partial view where complex rendering logic or code execution is required to render the markup.
Turns out that jquery.unobtrusive-ajax.js is not included by default. Adding it solved the problem.
As an additional note on getting this working. I'm hoping VS 2013 RTM includes this but either way this should get you up and running
install-package Microsoft.jQuery.Ajax.Unobtrusive
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*") );
@Scripts.Render("~/bundles/jquery")
or include it in each view you want to use it in
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With