MyTings
MyTings

Reputation: 1

How to display pop up on webpage after button click in MVC

I need to display a popup that will show the product description after clicking a button but it's not displaying.

<button onclick="@Html.Partial("ProductDetails")">Details</button>

Given that I have another page named ProductDetails

Upvotes: 0

Views: 7165

Answers (1)

Rob Smitha
Rob Smitha

Reputation: 405

You will need to use some AJAX to populate the partial view pop up. Here is a development approach I recommend. It uses jQuery and Bootstrap.

EDIT: I updated the code to pass productId to the controller. Also added an index method and page for clarity.

Create a method in your controller that will return the partial view (Assuming your view is named "ProductDetails").

public ActionResult Index()
{
    var products = _yourDatabase.Products;
    var model = products.Select(p => new new ProductDetailsViewModel
    {
      ProductID = productDetailsData.ID,
      //...fill in the rest of the properties
    }).ToList();
    return View(model);
}
public ActionResult ProductDetails(int productId)
{
  var productDetailsData = _yourDatabase.Products.SingleOrDefault(p => p.ID == productId);
  //you will need to create this class
  var model = new ProductDetailsViewModel
  {
    ProductID = productDetailsData.ID,
    //...fill in the rest of the properties
  };
  return PartialView(model)
}

In your partial view "ProductDetails", create the layout for your product details pop up. I just added ProductID for starters.

@model ProductDetailsViewModel
<p>ProductID: @Model.ProductID</p>

Now your button click and index page should look like this. Also add a pop up and create some javascript to load the partial view.

@model List<ProductDetailsViewModel>
@foreach(var item in Model)
{
<button onclick="GetProductDetailsPartial(@item.ID)">Details</button>
}

<div id="modal_product_details" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Product Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div id="div_product_details"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
function GetProductDetailsPartial(productId){
   $.get('YOUR_CONTROLLER/ProductDetails', { productId: productId } function(data){
      $('#div_product_details').html(data)
      $('#modal_product_details').modal('show')
   })
}
</script>

Hopefully this helps you. Please let me know if you need to make this work for multiple products which can be done by passing a ProductID to the javascript then controller.

Upvotes: 1

Related Questions