How to render a partial view (using razor) after user click?
Solution 1
Try this
@Html.ActionLink("Pages","Pages","Home",new {@is=Model.ID},new {@class="menu"})
@Html.ActionLink("Posts","Posts","Home",new {@is=Model.ID},new {@class="menu"})
<div id="detailView"></div>
And have some javascript to listen to the click event on these links and use jQuery load method to load the result from the action methods.
<script type="text/javascript">
$(function(){
$("a.menu").click(function(e){
e.preventDefault();
$("#detailView").load($(this).attr("href"))
});
});
</script>
Assuming you have the Action methods in your HomeController
which returns the relevant view/partial view.
Solution 2
try this
$.get( '@Url.Action("Location","Location", new { id = Model.ID } )',
function(data) {
$('#detailsDiv').html(data);
});
Related videos on Youtube
Omri
Updated on June 21, 2022Comments
-
Omri almost 2 years
I've been searching for a solution, but every thing I tried didn't help, although it seems very easy. I'm sure some of you will know what should I do.
I am using ASP.NET MVC4 (razor). I have a side menu, and all I want is that another partial view will be rendered (depends on the menu item's being clicked). I have a div on my page that should contain this partial view. The command:
@Html.Partial("_TitleDescription")
works just fine, but it's statically render the partial view (on compilation time). I want it to render it dynamically with every button the user clicked in the menu.
I tried:
@Ajax.ActionLink("Location", "Location", "Product", new { id = @Model.ID }, new AjaxOptions() { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"})
I tried:
<script type="text/javascript"> function getView() { $('#detailsDiv').load("@Url.Action("Location" , "Product" )"); } </script> <a href='javascript:getView();'>Get Partial View</a> <div id="detailsDiv"></div>
and also like this:
<div id="detailsDiv"> @{ Html.RenderPartial("_TitleDescription", null); } </div>
but nothing works for me.
EDIT:
I tried the two answers but non of them works... so here is my controller:
public ActionResult Location(int id = 0) { Product product = unitOfWork.ProductRepository.GetById(id); return PartialView("Location.cshtml", product); }
I put a breakpoint and I'm hitting it every time, but still nothing is changing in the view... :(
This is what i tried again:
<div id="detailsDiv"></div> <a href="#" onclick="loadLocation()">Location</a> <script type="text/javascript"> function loadLocation() { $.get('@Url.Action("Location","Product", new { id = 15 } )', function (data) { $('#detailsDiv').load(data); }); } </script>
and I also tried this:
<div id="detailsDiv"></div> @Html.ActionLink("Pages","Location","Product",new {id = 15},new {@class="menu"}) <script type="text/javascript"> $(function () { $(".menu").click(function (e) { e.preventDefault(); $("#detailsDiv").load($(this).attr("href")) }); }); </script>