hamid hamid - 1 year ago 86
ASP.NET (C#) Question

how to load selected partialview in a view in asp mvc?

I am working on ASP.NET Mvc project. i have a view similar to image:

enter image description here

I design right panel in layout. my layout code:

<div class="col-md-3 panel panel-info" style="margin-top:20px;">
<div class="panel panel-primary" style="margin-top:8px;">
<div class="panel-heading">Setting</div>
<div class="panel-body">

<div class="list-group">

<a href="#" class="list-group-item active text-center">Lists</a>
<hr />
<a href="#" class="list-group-item">Add Users - Partialview 1</a>

<a href="~/Areas/Admin/Views/Shared/_AddUser.cshtml" class="list-group-item">Edit Users - Partialview 2</a>

<a href="~/Areas/Admin/Views/Shared/_UserList.cshtml" class="list-group-item">User List - Partialview 3</a>

<a href="#" class="list-group-item">Set Password - Partialview 4</a>

<a href="#" class="list-group-item">User Details - Partialview 5</a>

<a href="#" class="list-group-item">Send Message - Partialview 6</a>


I have several modes in right panel contains : Add,Edit,List and ...
Each mode has a special Partialview. I want, when i click on every mode on right panel, special partialview load in left side. how can i load dynamically partialview in asp mvc?


Answer Source

Method 1

First you need to make an action to the controller like this in your view

     @{Html.RenderAction("youractionname", "controllername");}

and then on controller you need to return partial view like this

public ActionResult youractionname()
            return PartialView("~/Areas/Admin/Views/Shared/_AddUser.cshtml");

by this method your partial view will be loaded in your view.

Method 2

You can use ajax to load the partialview without refreshing the browser.

First you need to add a div with some id where you need to load the partial view.

  <div id="PartialId"></div>

then you need to add the action link (on click of the link partial view will be loaded)

<a href="javascript:Details()">Select</a>

Your ajax method looks like below

    function Details() {
            url: '@Url.Action("index", "Home")', // your action method
            method: "POST", // your method
            cache: false,
            data: { }
        }).done(function (result) {

Note you need to add u add Unobtrusive-Ajax-jquery script to your project.

You can find this here