Karthikeyan Murthy
Karthikeyan Murthy

Reputation: 61

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

Upvotes: 5

Views: 14376

Answers (2)

drichardson
drichardson

Reputation: 140

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");
}

Upvotes: 2

Joseph Woodward
Joseph Woodward

Reputation: 9281

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");
}

Upvotes: 6

Related Questions