Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ActionLink to open Modal and pass parameter in MVC

I am trying to open my bootstrap modal on the same page by clicking on the ActionLink and passing a parameter as below:

@foreach (Items item in Model)
{
  @Html.ActionLink("Download", "#", new { data-id = '@item.Name' } )
}

//Modal
<div id="dModal" class="modal hide fade" aria-hidden="true">
   <div class="modal-body">
      @using (Html.BeginForm("getCSV", "Download", new { filename = data-id }, FormMethod.Post, null))
      {
        <button id="btnCSV" type="submit">Download CSV</button>
      }
      //other options for excel, word etc
   </div>
</div>

In the ActionLink I have kept actionName parameter to #, this is because the modal is on the same page and the action will be decided when the user selects the options in the modal. The reason for not calling the download action method directly is because the user has options to download in various formats excel, csv etc.

like image 538
user2906420 Avatar asked Oct 01 '22 21:10

user2906420


2 Answers

This is how I show a bootstrap modal form using an html.actionlink

@Html.ActionLink("ModalPopUp", "#", new { id = parameter }, new { @data_toggle = "modal", @data_target = "#YourModalId"}) 
like image 51
NesNej Otto Avatar answered Oct 07 '22 18:10

NesNej Otto


Opening a bootstrap modal dialog doesn't require you to use an ActionLink and as Adriano mentions above you're confusing client and server code.

A bootstrap modal can be manipulated using the following options as described in this question.

$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');

and in your case your code should look something like this.

@foreach (Items item in Model)
{
  <a href="javascript:void(0);" data-id="@item.Name" class="OpenDialog">Download</a>
}

$(function () {
    $(".OpenDialog").click(function (e) {
        $('#myModal').modal('show');
    });
});

In terms of passing data to the modal that's really a separate question but it is covered here.

Basically you can handle the click event and put the value in a visible or hidden field (whichever is appropriate).

So you might change the above code to something like this

$(function () {
    $(".OpenDialog").click(function (e) {
        $("#myModal #id").val($(this).data("id"));
        $("#myModal").modal('show');
    });
});

and now you have the value stored in your modal which can be accessed as required.

like image 30
Maxim Gershkovich Avatar answered Oct 07 '22 16:10

Maxim Gershkovich