Open the view in popup in asp.net MVC action click

28,633

Solution 1

Add custom attribute to the link, use its URL to load the PartialView from controller in the modal form.

View:

@Html.ActionLink("View Clients", "Details", "Client", new { id = item.Id }, new { data_modal = "" })

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

Javascript:

$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {        
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');
        });
        return false;
    });
});

Controller:

public class ClientController : Controller
{
  public ActionResult Details(long id = 0)
    {
        Client client = db.Clients.Find(id);
        if (client == null)
        {
            return HttpNotFound();
        }
        return PartialView(client);
    }
}

Reference: http://www.advancesharp.com/blog/1125/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-1 http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2

Note: ASP MVC will automatically convert underscores in html attribute properties to dashes. https://stackoverflow.com/a/4515095/3387187

Solution 2

Use an ajax call to return the partial view and add it to the DOM.

var url = '@Url.Action("Details", "Client")';

$('selector').load(url, { id: 1 });
Share:
28,633
Andy Eng
Author by

Andy Eng

Updated on July 09, 2022

Comments

  • Andy Eng
    Andy Eng almost 2 years

    I am working on small POC of asp.net mvc scaffolding. I have one action link which calls another controller's action method which in turn opens up the view of that action method. But i want that view to be open in popup not in new tab. Following is the code of action link

    @Html.ActionLink("View Clients", "Details", "Client", new { id=item.Id})
    

    In above code 'View Clients' is the link name which calls 'Details' method of 'Client controller' which passes ID as parameter as well. Following is the Client controller:

     public class ClientController : Controller
    {
      public ActionResult Details(long id = 0)
        {
            Client client = db.Clients.Find(id);
            if (client == null)
            {
                return HttpNotFound();
            }
            return View(client);
        }
      }
    

    Above controller method returns the details view of Client controller.

    So what i want to do here is to open that particular view in the popup. Does anybody have solution on this ?