Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Partial View show as full page in MVC 5 Visual Studio 13?

Tags:

asp.net-mvc

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.

like image 667
Jesse Liberty Avatar asked Aug 30 '13 20:08

Jesse Liberty


People also ask

How can you display the partial view on the main page?

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.

How do you render a partial view inside a view in MVC?

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.

Can we have layout for partial view?

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.


2 Answers

Turns out that jquery.unobtrusive-ajax.js is not included by default. Adding it solved the problem.

like image 169
Jesse Liberty Avatar answered Oct 18 '22 15:10

Jesse Liberty


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 jquery-validate via nuget by going to tools-library package manager->package manager console and entering in
install-package Microsoft.jQuery.Ajax.Unobtrusive
  • Configure your bundle in your /app_start/bundleconfig.cs
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
    "~/Scripts/jquery.unobtrusive*",
    "~/Scripts/jquery.validate*")
);
  • Add your bundle to your _layout.cshtml either beneath your
@Scripts.Render("~/bundles/jquery")

or include it in each view you want to use it in

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
like image 28
Adam Tuliper Avatar answered Oct 18 '22 15:10

Adam Tuliper