I am trying to render partial view from controller on button click event to view the details. But unfortunately its not working.
My Controller Action
OwnerController.cs
public IActionResult ShowpopUp(int id) {
var venue = _context.Venues.FirstOrDefault(x=>x.Id==id);
return PartialView(venue);
}
My View All.cshtml
#model List<Venue>
<table class="table table-hover">
<thead>
<th> Property Name </th>
<th colspan="2">Action</th>
</thead>
<tbody>
#foreach(var x in Model)
{
<tr>
<td>
#x.Name
</td>
<td>
<a class="btn btn-default btn-sm" id="#x.Id" onclick="Details(this.id)">Show</a>
</td>
</tr>
}
</tbody>
</table>
<script>
function Details(id)
{
$.get("#Url.Action("ShowpopUp","Owner")/"+id,
function(data) {$('.modal-body').html(data);})
$("#myModal").modal("show");
}
$('#myModal').on('hidden.bs.modal', function(e){
$('.modal-body').html("");
})
}
</script>
myModal
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The following example should help achieve your requirement of rendering partial view as modal popup using jQuery Ajax, please check it.
All.cshtml
#model IEnumerable<Venue>
#{
ViewData["Title"] = "All";
}
<h1>All</h1>
<table class="table table-hover">
<thead>
<th> Property Name </th>
<th colspan="2">Action</th>
</thead>
<tbody>
#foreach (var x in Model)
{
<tr>
<td>
#x.Name
</td>
<td>
<a class="btn btn-default btn-sm" id="#x.Id" onclick="Details(this.id)">Show</a>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
function Details(id) {
$.get("#Url.Action("ShowpopUp","Owner")/" + id,
function (data) {
$('.modal-body').html(data);
});
$("#myModal").modal("show");
}
</script>
}
ShowpopUp action
public IActionResult ShowpopUp(int id)
{
var venue = _context.Venues.FirstOrDefault(x => x.Id == id);
//specify the name or path of the partial view
return PartialView("_VenueDetail", venue);
}
_VenueDetail.cshtml (partial view under Views/Shared folder)
#model Venue
<h1>Venue Details</h1>
<h2>Id: #Model.Id</h2>
<h2>Name: #Model.Name</h2>
Test Result
Hard to explain in my title but essentially what I'm trying to achieve:
I have a view which displays some client Info in a table:
#foreach (var item in Model.Where(x => x.User == User.Identity.GetUserName()))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Client_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Client_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact_Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Contact_Mobile)
</td>
<td>
<input type="button" data-toggle="modal" data-target="#sendFormModal" class="btn btn-primary" value="Send Form" onclick="# " />
</td>
</tr>
}
From here, each Item generates a row and within each row I have a button. I am looking to link the item.Id and other info with that button, so when I click the button it opens a modal and I can use the ID to get other data from my table.
The modal requires some input from the user, before another button sends an email. Hence, I require to get some other info from my table (email address included). I have the rest of the process working, but just cannot figure out how to pass any of the data from that row to the modal/button on the same row.
Modal Code FYI
<!-- Modal -->
<div class="modal fade" id="sendFormModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Send Client Data</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Select a Form</p>
<select class="form-control" id="formSelection">
<option></option>
<option>Test</option>
</select><br />
<p>Input your custom message</p>
<textarea class="form-control" id="formMessage"></textarea>
</div>
<div class="modal-footer">
<button type="button" onclick="SendClientForm()" class="btn btn-success" data-dismiss="modal">Send</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
So I have a list of web urls, all fetched from SQL and has an id, an address etc.
I list them in a table using the following:
<div>
<div class="well" margin-left:20px; margin-right:20px">
<h2 style="margin-left:20px; margin-top:10px">Control Added Links</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>
Link Address
</th>
<th>
Check Interval
</th>
<th>
Status
</th>
<th>
#
</th>
</tr>
</thead>
<tbody>
#foreach (var i in links)
{
<tr>
<td>
#i.Address
</td>
<td>
#i.Interval
</td>
<td>
#if (i.Status)
{ <text> ON </text>}
else
{ <text> OFF </text>}
</td>
<td>
<a href="~/Control/Delete/#i.Id">
✖
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
"links" here is a list of Link models:
#{
var links = (List<Link>)ViewData["LinkInfos"];
}
Right now, there is an X button you can click to delete a link from database, by using i.Id of the item 'i'. What I want to do is, ask for a confirmation with a modal, instead of directly deleting.
I delete the link with a function inside controller using the follownig:
public ActionResult Delete(int Id)
{
UserLinks links = new UserLinks();
links.delete(Id, User.Identity.Name);
return RedirectToAction("Index");
}
I changed this code, managed to pass the data from button to modal:
<a data-toggle="modal" data-id="#i.Id" data-request-url="#Url.Action("Delete", "Control")" title="Delete link" class="delete-Link btn btn-danger" href="#deleteLink">
✖
</a>
<div id="deleteLink" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Test</h4>
</div>
<div class="modal-body">
This will delete all records related to this link. Are you sure?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="deleteConfirm()">Yes</button>
<button class="btn btn-warning" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
var myLinkId
var url
$(document).on("click", ".delete-Link", function () {
myLinkId = $(this).data('id');
url = $(this).data('request-url');
$(".modal-body #linkId").val(myLinkId);
// As pointed out in comments,
// it is superfluous to have to manually call the modal.
// $('#addBookDialog').modal('show');
});
function deleteConfirm()
{
debugger;
$.post(url), { Id: myLinkId };
}
</script>
But problem right now is passing this data from modal to controller. I wrote the "deleteConfirm" function but it doesn't seem to work, it doesn't go to ~/Control/Delete.
First part of my question is actually solved, I can pass id from button to modal, but I am not sure if it is properly solved so I am asking for that too, I currently pass the id using JavaScript but wonder if I can directly pass from button to modal itself.
I managed to fix my issue and properly delete by creating a modal for each item... which I assume is the sloppy way and can be a problem when I have like, let's say 100 links.
One solution I have in mind but don't know how to implement:
Have a "globalId" parameter inside view, when a button is clicked, i.Id is assigned to globalId, then open the modal, which has globalId as a parameter inside. Just like with , use inside modal, which changes by deletion button you click. But problem is, don't know how to create this global parameter and assign i.Id to it with click of a button.
A way I think I can implement my possible solution:
I want to have a variable in a view, let's say int globalId.
Let's say I press the delete button for id = 10, what I want to happen is simply have "global = id" so I want to assign 10 to number. If id of button is 12, I want "global = id" to happen again, this time to assign 12 to number.
So this way, modal will just use globalId, so I can make it have:
Yes
This way, there will only be one modal, every button will open the same modal and modal will use the same variable. Just value for globalId assigned to this modal will change with click of a button.
Question is, how can I create this local variable and how can I simply assign a new value to this local variable?
I have made some changes in your view which make this possible to work. I have added one hidden field in model and store the id on show event of the model. And on confirm id is get from this hidden field to construct the post url.
<a data-toggle="modal" data-id="#id" data-request-url="#Url.Action("Delete", "Home")" title="Delete link" class="delete-Link btn btn-danger" href="#deleteLink">
✖
</a>
<div id="deleteLink" class="modal fade" role="dialog">
<div class="modal-dialog">
<input type="hidden" id="linkId" />
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Test</h4>
</div>
<div class="modal-body">
This will delete all records related to this link. Are you sure?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="deleteConfirm()">Yes</button>
<button class="btn btn-warning" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
$('#deleteLink').on('show.bs.modal', function (e) {
$("#linkId").val($(e.relatedTarget).data('id'));
});
function deleteConfirm()
{
var url = "#Url.Action("Delete", "Control")/" + $("#linkId").val();
$.post(url).success(function () {
location.href = "#Url.Action("Index", "Control")";
});
}
</script>
I have readed a lot of blogs and articles about showing MVC partial views using Boostrap modals. It seems that I have exactly what I'm seen on the material consulted but still it doesn't show the modal. I just need to show the partial view with the Album details in a modal. The controller is working fine when I load the URL through the browser.
This is the Index HTML code where the modal is shown:
<tbody>
#foreach( var album in Model.Albums)
{
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
}
</tbody>
Partial View
<div class="modal fade" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="albumModalLabel">Album Details</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<div class="row">
<label>Album<input class="form-control" type="text" id="title" /></label>
</div>
<div class="row">
<label>Artist <input class="form-control" type="text" id="artist" /></label>
</div>
<div class="row">
<label>Genre <input class="form-control" type="text" id="genre" /></label>
</div>
<div class="row">
<label>Year <input class="form-control" type="text" id="year" /></label>
</div>
</div>
<div class="col-md-8">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Track</th>
<th>Song Title</th>
<th>Length</th>
</tr>
</thead>
<tbody class="tracks"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
HomeController
[HttpGet]
public ActionResult Album(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var albumInfo = _service.GetAlbumInfo((int) id);
if (albumInfo == null) return HttpNotFound();
return PartialView("_Album", albumInfo);
}
Script
$(document).ready(function() {
$('.list-element').click(function () {
debugger;
var $buttonClicked = $(this);
var url = $buttonClicked.attr('data-url');
$.get(url, function (data) {
$('#albumContainer').html(data);
$('#albumModal').modal('show');
});
});
});
In almost all of the SO questions counsulted, they wasn't using data-target but I am. What do I need to modify to achieve that the modal shows?
VIEW
#model ShowModal
<table>
<tbody>
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModal">
#Html.Partial("_albumPartial", Model)
</div>
CONTROLLER
[HttpGet]
public ActionResult Album(int? id)
{
ShowModal modal = new ShowModal();
var albumInfo = _service.GetAlbumInfo((int) id);
modal.Info1 = albumInfo.Info1;//and other fields
return PartialView("_albumPartial", modal);
}
SCRIPT
<script>
$(document).ready(function () {
$("#albumModal").on("show.bs.modal", function (e) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // or button.attr("data-url") or get here just the id and create the URL here
$.get(url, function (data) {
$('#albumModal').html(data);
$('#albumModal').modal('show');
});
});
});
</script>
I am trying to make a dialog with bootstrap modal to confirm a delete. The delete works well, except it doesn't get the data which I select but it gets the first data in ID order from the database. I am new on client-side programming, so if someone could help me it would be nice.
The code is:
[HttpPost]
public async Task<ActionResult> Delete(int id)
{
RepFilter repFilter = await db.RepFilters.FindAsync(id);
db.RepFilters.Remove(repFilter);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
(razor)
#foreach (var item in Model)
{
using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
{
<tr>
<td>#index</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Report.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">Delete</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">Are you sure you want to delete: <span><b>#item.Description</b></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Delete" class="btn btn-danger" />
</div>
</div>
</div>
</div>
</td>
</tr>
}
}
</tbody>
The button that opens the modal is getting the right ID, but the modal doesn't!
So how to make the modal take the adequate data to delete?
I am trying to avoid writing javascript and use data attributes, until there is no other choice
The modal this way has the same ID, no matter which data you try to delete.
So just add a variable to specify different ID for the mmodal:
using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
{
var myModal = "myModal" + item.ID;
<tr>
<td>...</td>
<td>...</td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="##myModal">Delete</button>
<!-- Modal -->
<div class="modal fade" id="#myModal" tabindex="-1" role="dialog" data-keyboard="false" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm">
...........<!--And the rest of the modal code-->
There are actually quite a few things you may want to address in your view. You are looping through the items in your model, and creating a separate form (and modal)for each item. This is probably not ideal, however if you really want to do it this way you can add a reference to the item id within the html for the modal. Just add a hidden input and set it's value to item.id.
However, I would not recommend this approach. I'm not certain for your reasons on wanting to shy away from JavaScript, but the functionality you want to create here is actually pretty basic.
See this post: Confirm delete modal/dialog with Twitter bootstrap?
Edit:
#foreach (var item in Model)
{
<tr>
<td>#index</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Report.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
<button type="button" class="btn btn-danger btn-sm" data-item-id="#item.ID" data-item-description="#item.Report.Description" data-toggle="modal" data-target="#confirm-delete">Delete</button>
</td>
</tr>
}
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">
Are you sure you want to delete: <span class="description"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Delete" class="btn btn-danger" />
</div>
</div>
</div>
<script>
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('itemId');
$modalDiv.addClass('loading');
$.post('/RepFilters/Delete/' + id).then(function () {
$modalDiv.modal('hide').removeClass('loading');
});
});
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.description', this).text(data.itemDescription);
$('.btn-ok', this).data('itemId', data.itemId);
});
</script>
You first write a delete function in jquery .for displaye confirm message you can use sweetalert and write a custom file for sweetalert.
yo must add refrence sweetalert css and script in your view page.
function Delete(id) {
var submitdelete=function(){ $.ajax({
url: '#Url.Action("/mycontroller/Delete)',
type: 'Post',
data: { id: id }
})
.done(function() {
$('#' + id).remove();//if you want to delete table row
msgBox.success("Success","Ok");
});}
msgBox.okToContinue("warning", "Are you sure to delete ?", "warning", "ok","cancel", submitdelete);
}
Confirm dialog
var msgBox = {
message: {
settings: {
Title: "",
OkButtonText: "",
type:"info"
}
},
okToContinue: function(title, text, type, okButtonText,closeButtonText, isConfirmDo) {
swal({
title: title,
text: text,
type: type,
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: okButtonText,
cancelButtonText: closeButtonText,
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
isConfirmDo();
}
});
},
confirmToContinue: function(title, text, type, confirmButtonText, cancelButtonText, isConfirmDo, isNotConfirmDo, showLoader) {
if (!showLoader) {
showLoader = false;
}
swal({
title: title,
text: text,
type: type,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButtonText,
closeOnConfirm: true,
closeOnCancel: true,
showLoaderOnConfirm: showLoader
},
function(isConfirm) {
if (isConfirm) {
isConfirmDo();
}
});
} ,
success: function (title, text,okButtontex) {
swal({
title: title,
text: text,
type: "success",
confirmButtonText: okButtontex
});
},
info: function (title, text) {
swal({
title: title,
text: text,
type: "info",
confirmButtonText: "OK"
});
},
warning: function (title, text) {
swal({
title: title,
text: text,
type: "warning",
confirmButtonText: "OK"
});
},
error: function (title, text) {
swal({
title: title,
text: text,
type: "error",
confirmButtonText: "OK"
});
},
}
Here's an easy way to do this. You should be able to adapt what i did here to your case. This requires very little javascript code.
<script>
var path_to_delete;
var root = location.protocol + "//" + location.host;
$("#deleteItem").click(function (e) {
path_to_delete = $(this).data('path');
$('#myform').attr('action', root + path_to_delete);
});
</script>
<table class="table table-hover" id="list">
<thead class="bg-dark text-white">
<tr>
<th>
Edit
</th>
<th>
Employee
</th>
<th>
Effective Date
</th>
<th>
ST/OT/DT
</th>
<th>
Other Pay
</th>
<th>
Job
</th>
<th>
Pending?
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<a class="btn btn-sm" href="~/Employees/TerminationEdit/#item.Employee_Termination_Info_Id">
<i class="fa fa-lg fa-pencil-alt text-dark"></i>
</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Name_Number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Effective_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Time)
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Other_Pay)
</td>
<td>
#Html.DisplayFor(modelItem => item.Job_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Pending)
</td>
<td>
<a id="deleteItem" class="btn btn-sm" data-toggle="modal" data-target="#deleteModal"
data-path="/Employees/TerminationDelete/#item.Employee_Termination_Info_Id">
<i class="fa fa-lg fa-trash-alt text-danger"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
<!-- Logout Modal-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Are you sure you want to delete this termination record? <br /><span class="text-danger">This cannot be undone.</span></div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
#using (Html.BeginForm("TerminationDelete", "Employees", FormMethod.Post, new { id = "myform", #class = "" }))
{
#Html.AntiForgeryToken()
<input type="submit" value="Delete" id="submitButton" class="btn btn-danger" />
}
</div>
</div>
</div>
</div>
So what happens here, is that the page will cycle through the model and draw the delete button (using font awesome). Note that here is is setting the data-path attribute for later use. When the button is clicked, it sets the form action for the button on the modal popup immediately. This is important, since it has a form around the delete button, it will send it to a POST and not a GET, as Rasika and Vasil Valchev pointed out. Plus, it has the benefit of the anti-forgery token.