Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load partial view on clicking Html.ActionLink?

Can someone please tell me on how to load PartialView in the same page when clicking on Html.ActionLink. I have listed down my requirements below.

  1. I have an Index page which will list the employees from Employee table, also each row in a table will have Edit & Delete link (Html.ActionLink) to update/delete the employee information.
  2. Also, Index page will have partial view with textboxes to create new employee (or) editing an existing employee.
  3. When user select Edit link from the table, appropriate user details has to be loaded in the textboxes of partial view to update the employee detail.
  4. Also, new employee details entered in partial view should get stored into the DB table and at the same time it should get added into the table in Index page.

All the above steps should handle without using Ajax in MVC5. Can anyone please help me to achieve the above steps? Your help is much appreciated

like image 419
Karthikeyan Murthy Avatar asked Nov 20 '14 01:11

Karthikeyan Murthy


2 Answers

Once your view is rendered the only way to load a partial view is via an Ajax call which returns the partial view to your JQuery/Javascript and then updates the DOM accordingly.

For instance:

Your HTML

<a href="#" id="loadViewButton">Load view</a>
<div id="partialViewContainer"><!-- your partial view will be loaded in here --></div>

Your JQuery:

$('#loadViewButton').on('click', function() {
    $.ajax({
        type: "GET"
        url: '/YourController/YourAction',
        success: function (data, textStatus, jqXHR) {
            $('#partialViewContainer').html(data);
        }
    });
});

Your controller action:

[HttpGet]
public ActionResult YourAction()
{
  return View("YourView");
}
like image 128
Joseph Woodward Avatar answered Sep 20 '22 17:09

Joseph Woodward


When using an ActionLink, this works really well for me.

HTML

@Html.ActionLink("Load Partial Action Link", null, null, null, new { id = "loadPartialActionLink" })
<div id="AJAXContainer"></div>

jQuery

$('#loadPartialActionLink').on('click', function (e) {
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: '/MyController/_MyPartial',
        success: function (data, textStatus, jqXHR) {
            $('#AJAXContainer').html(data);
        }
    });
});

Controller Action

[HttpGet]
public ActionResult _MyPartial()
{
    return PartialView("_MyPartial");
}
like image 20
drichardson Avatar answered Sep 19 '22 17:09

drichardson