Thursday, 5 January 2017

Calling a action/controller with params and showing a partial view in modal dialog in MVC3/4/5

Pretty much every MVC user application you write need a modal popup or even modal form dialog containing a partial view.
Therefore we need a mechnism for calling an action and controller , passing in an Id and returning a view model with results to a partial view inside a modal dialog.

There are many different options now but i always go back to this method when i need to achieve this as it gives me so much control not only over the params i can pass in ,but dialog size and style too.

This is the jquery code , i copy this to a separate js file in the project script directory.

$(document).ready(function () {
      $(".openDialog").on("click"function (e) {
          e.preventDefault();
          $("<div></div>")
              .addClass("dialog")
              .attr("id", $(this)
              .attr("data-dialog-id"))
              .appendTo("body")
              .dialog({
                  title: $(this).attr("data-dialog-title"),
                  close: function (ev, ui) { window.location.reload() }, //function () { $(this).remove() },
                  width: 600,
                  modal: true,
                  height: 'auto',
                  show: 'fade',
                  hide: 'fade',
                  resizable: 'false',
 
                  //buttons: {
                  //    "Close": function ()
                  //    { $(this).dialog("close"); }
                  //}
              })
 
 
          .load(this.href);
       
 
      });
 
   
 
      $(".close").on("@Html.ActionLink("Edit""EditDocumentDetails""Document",
             new { id = item.DocumentId }, 
             new 
             {     @class = "openDialog", 
                   data_dialog_id = "interestDialog", 
                   data_dialog_title = "Edit Document Details" 
             })click"function (e) {
          e.preventDefault();
          $(this).closest(".dialog").dialog("close");
      });
   
  });


An example of where this is called from a view is :

@Html.ActionLink("Edit""EditDocumentDetails""Document",
             new { id = item.DocumentId }, 
             new 
             {     @class = "openDialog", 
                   data_dialog_id = "interestDialog", 
                   data_dialog_title = "Edit Document Details" 
             })

And an example of your controller code :

public ActionResult EditDocumentDetails(int id)
      {
          var doc = this.context.ApplicantDocuments.Find(id);
          if (doc == null)
          {
              return HttpNotFound();
          }
 
          IEnumerable<SelectListItem> docTypes = this.GetReferenceList(Constants.ReferenceDocumentTypeList);
          ViewBag.DocumentTypes = new SelectList(docTypes, "Value""Text", doc.DocumentTypeRef);
          
          return PartialView("_EditDocumentDetails", doc);
      }

No comments:

Post a Comment