ProgrammerGuide.Net | Step by Step Programmer Guide

Loading PartialView Via JQuery In ASP.NET MVC | Returning PartialView From ASP.NET MVC Action | ASP.NET MVC Tutorial

Let’s take a scenario where we want to load different ASP.NET MVC Partial Views based on dropdownlist selection.

A Sample code of ASP.NET MVC view is given below. Notice that there is a place holder div, partialPlaceHolder which would have its html replaced when an item is selected in the dropdown.
<!-- Some stuff here. Dropdown and so on-->
<!-- Place where you will insert your partial -->
<div id="partialPlaceHolder" style="display:none;"> </div>

How to replace an html of div using jQuery?
Below jQuery code snippet binds a function to the change event of a dropdown list, myDropDown. This bonded function gets the partial view via jquery ajax call and loads it to place holder.
/* This is change event for your dropdownlist */
$('#myDropDown').change( function() {
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
/* Request the partial view with .get request. */
$.get('/Controller/MyAction/' + selectedID , function(data) {
/* data is the pure html returned from action method, load it to your page */
/* little fade in effect */

How to return an ASP.NET MVC PartialView from ASP.NET MVC controllers action?
This can be achieved using a virtual method, PartialView in ASP.NET MVC Controller. In this case, our  controller action which is /Controller/MyAction is called in the above jquery function and the action MyAction returns the partial view.
// GET: /Controller/MyAction/{id}
public ActionResult MyAction(int id)
var partialViewModel = new PartialViewModel();
// TODO: Populate the model (viewmodel) here using the id
return PartialView("_MyPartial", partialViewModel );

Please click here for related products on Amazon!


Add comment

Want to Check Celebrities News?