BootBox javascript Confirm delete - javascript

I am using asp.net MVC 5.
In Bootbox js
$(document).on("click", ".MyLink", function (e) {
bootbox.confirm("Are you sure?", function(result) {
Example.show("Confirm result: "+result);
});
});
#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { #class = "MyLink" })
How to delete the HTML action link ?
Please find the full details of the code:-
Javascript code:-
<script src="~/Scripts/bootbox.min.js"></script>
$(document).on("click", ".MyLink", function (e) {
var self = this;
bootbox.confirm("Are you sure?", function (result) {
Example.show("Confirm result: " + result);
$(self).remove();
});
});
HTML Code:-
<h2>Index</h2>
<p>Content here. <a class="MyLink" href=#>Alert!</a></p>
<p>
#Html.ActionLink("Create New", "Create")
</p>
Also see the inside<table> code for your
reference:-
<table class="table">
<tr>
<th> First Name </th>
<th> Last Name </th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td> #Html.DisplayFor(modelItem => item.FirstName) </td>
<td> #Html.DisplayFor(modelItem => item.LastName) </td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
#Html.ActionLink("Details", "Details", new { id = item.CustomerID }) |
#*#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID, #class = "MyLink" })*#
Delete
</td>
</tr>
}
Also see the Controller code for your reference:-
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
if (customer == null)
{
return HttpNotFound();
}
return RedirectToAction("Index");
//return View(customer);
}

Related

Get the HTML table Checked item Id's to list and Pass to Controller

In my ASP.NET MVC project, there is a table that shows the user view the information of file type and Id (Hidden).
Whenever the user put checked the checkboxes and clicks on the Send Request Mail Button, I want to get the IDs of the checked rows and pass them to the controller as a List of Ids.
This is the table view
<tbody>
#foreach (var item in Model.ReqDocumentsViewModel.OrderByDescending(x => x.Id))
{ <tr class="even pointer">
<td style="display:none;">#item.Id</td>
<td>#item.FileType</td>
<td>#item.Note</td> #if (item.RequestStatus == false) { <td> Not Requested; </td> } else { <td> Requested; </td> } <td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
<button type="button" class="btn btn-primary sm" onclick="SendMailNotification();">Send Request Mail</button>
This is what I tried.
function SendMailNotification() {
const selectedRows = [...$('table tbody tr:has("input:checked")')]
.map(tr => [...$(tr).find('td:lt(1)')]
.reduce((res, td) => (res[$(td).attr('prop')] = $(td).text(), res), {}))
console.log(selectedRows)
var newOrders = $.map(selectedRows, function (element) {
var obj = {};
for (var key in element) {
obj.Id = key;
}
return obj;
});
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: JSON.stringify(newOrders),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r == false) {
alert("You have to enter Order Qty first");
} else {
alert("Order Created");
location.reload();
}
}
});
}
In Controller
public JsonResult RequestDocument(List < ReqDocList > idQs)
{
}
Model
public class ReqDocList
{
public int Id { get; set; }
}
I want to get the IDs of the checked rows and pass them to the
controller as a List of Ids.
Below is a work demo, you can refer to it.
ReqDocListVM:
public class ReqDocListVM
{
public ICollection<ReqDocList> ReqDocList { get; set; }
}
TaskController:
public class TaskController : Controller
{
public static List<ReqDocList> ReqDocList = new List<ReqDocList>()
{
new ReqDocList() {Id =1},
new ReqDocList() {Id =2},
new ReqDocList() {Id =3},
new ReqDocList() {Id =4}
};
public IActionResult Index()
{
var model =new ReqDocListVM();
model.ReqDocList= ReqDocList;
return View(model);
}
public JsonResult RequestDocument(List<int> ids)
{
return Json(ids);
}
}
Index view:
#model ReqDocListVM
<table class="table table-bordered table-light">
<tbody>
#foreach (var item in Model.ReqDocList)
{
<tr class="even-pointer" chk-id="#item.Id">
<td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
</table>
<button id="bt"type="button" class="btn btn-primary sm" >Send Request Mail</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var Ids = [];
$(".even-pointer").click(function () {
$(this).toggleClass("selected");
var Id = $(this).attr('chk-id');
if ($(this).hasClass("selected")) {
Ids.push(Id);
}
else {
Ids = Ids.filter(function (id) {
return id !== Id;
});
}
});
$("#bt").click(function () {
console.log(Ids);
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: { "ids": Ids },
success: function (response) {
alert(response);
}
});
});
});
</script>
result:

How to select all checkboxes and pass to controller

I build this code for select all checboxes and pass to controller, I using button when click it check all checkboxes and pick up all variables like (idtip, idemployee) trought array send to controller to update database table.
<tr>
<th>name</th>
<th>tips</th>
<th>
<button id="btnClick" class="btnClick">Select all</button>
</th>
</tr>
Here is my input and script.
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
<div class="pure-checkbox" idtip="#item.idtip">
<input type="checkbox" idtip="#item.idtip" class="checktip"
checked="#(item.idemployee == ViewBag.idemployee ? true : false)"
name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
<input type="hidden" value="#ViewData["idemployee"]" name="idemployee" id="idemployee" class="idemployee" />
<script>
$('.pure-checkbox').click(function () {
$(this).parents('td').toggleClass('chked')
})
var wantedids = [idemployee,idtip]
$("#btnClick").click(function () {
for (var i = 0; i < $('.pure-checkbox').length; i++) {
if ($('.pure-checkbox').eq(i).parents('td').hasClass('chked')) {
wantedids.push(
$('.pure-checkbox').eq(i).attr('idtip')
)
}
}
$.post("UrlSettingsDocument.Tips", { ids: wantedids },
)
})
I using button when click it check all checkboxes and pick up all
variables like (idtip, idemployee) trought array send to controller to
update database table.
You could refer the following sample code:
Create a ViewModel to display records:
public class TestViewModel
{
public int id { get; set; }
public int idtip { get; set; }
public string idemployee { get; set; }
public bool isChecked { get; set; }
}
In the Controller, add the following actions:
//Set the initial data and return to view.
public IActionResult Default()
{
List<TestViewModel> items = new List<TestViewModel>()
{
new TestViewModel(){ id=101, idtip=1001, idemployee="AAA" },
new TestViewModel(){id=102,idtip=1002, idemployee="BBB" },
new TestViewModel(){id=103, idtip=1003, idemployee="CCC" },
new TestViewModel(){ id=104,idtip=1004, idemployee="DDD" },
new TestViewModel(){id=105, idtip=1005, idemployee="EEE" }
};
ViewBag.idemployee = "CCC"; //set the default checked item.
return View(items);
}
public IActionResult AddItems(IEnumerable<TestViewModel> items)
{
//insert the items into database.
return Ok("OK");
}
Then, in the View page (Default.cshtml), using the following code to display the content:
Here we can use a select all checkbox, after checking it, will select all items.
#model IEnumerable<WebApplication.Models.TestViewModel>
#{
ViewData["Title"] = "Default";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox" id="btnSelectAll" class="btnClick" /> <label for="btnSelectAll">Select All</label>
</th>
<th>
#Html.DisplayNameFor(model => model.idtip)
</th>
<th>
#Html.DisplayNameFor(model => model.idemployee)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
<div class="pure-checkbox" idtip="#item.idtip">
<input type="checkbox" idtip="#item.idtip" data-idemployee="#item.idemployee" class="checktip"
checked="#(item.idemployee == ViewBag.idemployee ? true : false)"
name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
<td>
#Html.DisplayFor(modelItem => item.idtip)
</td>
<td>
#Html.DisplayFor(modelItem => item.idemployee)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
<button id="btnSubmit" class="btnClick">Submit</button>
At the end of the Default.cshtml page, using the following script to achieve the select all function and submit the records to the controller.
#section Scripts{
<script>
$(function () {
//If checked the select all checkbox, select all items. else unchecked.
$("#btnSelectAll").click(function () {
if ($(this).is(":checked")) {
$(".checktip").each(function (index, item) {
$(item).prop("checked", true);
});
}
else {
$(".checktip").each(function (index, item) {
$(item).prop("checked", false);
});
}
});
$("#btnSubmit").click(function () {
var testViewModels = [];
//using the class selector to loop through the checkbox list and get all items, if you want to get the checked items, add an if...else statement in the each function.
$(".checktip").each(function (index, item) {
var TestViewModel = {};
TestViewModel.idtip = $(this).attr("idtip");
TestViewModel.idemployee = $(this).attr("data-idemployee");
TestViewModel.isChecked = $(this).is(":checked");
testViewModels.push(TestViewModel);
});
$.ajax({
type: "Post",
url: "/Home/AddItems", //remember change the controller to your owns.
data: { items: testViewModels }, //the name ("items") should be the same with the parameter's name in the controller.
success: function (data) {
console.log(data)
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
}
The result as below:

MVC Razor view need to update controls with Javascript

I have an MVC website using Razor views. My Model is a List<Device>. In this particular view I need to enter a serial number for the device's box and, if it matches the device's serial number, change the dropdown enum from LabelPack to SystemPack. Finally, the controller will update the device's status in the DB.
Here is the relevant code from the view:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.SerialNumber)
</td>
<td>
<input type="text" id=#item.SerialNumber name=#item.SerialNumber oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10" id="#item.SerialNumber">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
My question is basically: How do I check if the input serial number matches the device's serial number and update the dropdown? I assume there is a way to do this with JavaScript so I am calling a JavaScript method with the onInput event. However, I don't know what to put in the JavaScript method.
Fortunately, a coworker was able to help me with this. I'm sorry I didn't give enough information in the initial question. I really thought there would be an easy way to do this but it seems there is now. Below is the complete code from my view in case someone else stumbles into the same problem.
#model IEnumerable<DHLScanner.Models.Device>
#{
ViewBag.Title = "LabelPackStationView";
}
#using (Html.BeginForm("LabelPackStation", "Device", FormMethod.Post, new { id = "frmPackStation" }))
{
<p>
Find by serial number: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
<div>
<h4>Device</h4>
<hr />
<dl class="dl-horizontal"></dl>
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.SerialNumber)
</th>
<th>
#Html.DisplayName("Box Serial Number")
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<span id="sp_#item.ID">#Html.DisplayFor(modelItem => item.SerialNumber)</span>
</td>
<td>
<input type="hidden" id="hdn_#item.ID" value="#item.ID" />
<input type="text" id="ser_#item.ID" oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control", id = "ddl_" + #item.ID, name = "ID" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</table>
<p id="test"> xyz</p>
<p id="links">
#Html.ActionLink("Back to Prep", "PrepStation", "Order", new { id = ViewBag.Order.ID }, null)
#{
if (ViewBag.ShowSystemPackView)
{
#Html.ActionLink("Advance to System Pack", "SystemPackStation", "Order", new { id = ViewBag.Order.ID }, null)
}
}
</p>
<input type="hidden" name="testField" value="a value here" id="testField" />
<input type="hidden" id="hdn_Url" value="#ViewBag.Url" />
<input type="hidden" id="hdn_OrderId" name="ID" value="#ViewBag.Order.ID" />
<button id="btn_Refresh" name="pageRefrersh" value="refresh">Refresh</button>
}
#*<form action="" method="post"></form>*#
<script type="text/javascript">
function RegisterEvents(){
$('input[id^="ser"]').blur(function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var lbl = $('span[id="sp_' + Id + '"]');
if ($(this).val() == lbl.html()) {
$('select#ddl_' + Id).val('3');
}
});
$('button[id="btn_Refresh"]').click(function () {
CollectDeviceData();
return false;
});
}
function CollectDeviceData() {
var devices = new Array();
// Collect Data
$.each($('input[id^="ser"]'), function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var orderId = $('input[id="hdn_OrderId"]').val();
var device = {};
device.Id = Id;
device.Status = $('select#ddl_' + Id).val();
device.OrderID = orderId;
devices.push(device);
});
var jsonObject = {
devices: JSON.stringify(devices)
};
//Return Data
var results = function (data) {
window.location.href = $('input[id="hdn_Url"]').val();
};
PostBack(jsonObject, results);
}
function PostBack(jsonObject, result) {
var url = $('input[id="hdn_Url"]').val();
$.ajax({
url: url,
type: 'post',
data: jsonObject,
success: result,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
$(document).ready(function () {
RegisterEvents();
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

MVC 5 Ajax refresh based on dropdownlist and button click

Below is code I found online sometime back. It refreshes section of form based on link click. I want to change this to have links in a DropDownList. Then based on its selection and a button click I want to perform the same action as link click.
I am having hard time figuring out how to read dropdownlist selected value. I tried searching here on SO, but not finding any simple example. Looks like most of them are based on javascript. I am hoping that there must be some simple solution without using javascript.
Controller
namespace WebApplication2.Controllers
{
public class HomeController : Controller {
DBEntities db = new DBEntities();
// GET: /AllUsers/
public ActionResult Index()
{
return View();
}
// Return all students
public PartialViewResult All()
{
List<AspNetUser> model = db.AspNetUsers.ToList();
return PartialView("_Users", model);
}
// Return Top3 students
public PartialViewResult Top3()
{
List<AspNetUser> model = db.AspNetUsers.OrderByDescending(x => x.UserName).Take(3).ToList();
return PartialView("_Users", model);
}
}
}
Partial View
#model IEnumerable<WebApplication2.Models.AspNetUser>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.PhoneNumber)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
</tr>
}
</table>
View
#{
ViewBag.Title = "Home Page";
}
<div style="font-family:Arial">
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<h2>Students</h2>
#Ajax.ActionLink("All", "All",
new AjaxOptions
{
HttpMethod = "GET", UpdateTargetId = "divStudents", InsertionMode = InsertionMode.Replace
})
<span style="color:Blue">|</span>
#Ajax.ActionLink("Top 3", "Top3",
new AjaxOptions
{
HttpMethod = "GET", UpdateTargetId = "divStudents", InsertionMode = InsertionMode.Replace
} )
<br /><br />
<div id="divStudents" style="height: 600px; overflow: auto;"></div>
</div>
You need to replace you Ajax.ActionLink()'s with a single Ajax.BeginForm() containing the dropdownlist
#model StudentSearchVM
<h2>Students</h2>
#using (Ajax.BeginForm("Filter", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "divStudents", InsertionMode = InsertionMode.Replace }))
{
#Html.DropDownListFor(m => m.Filter, Model.FilterList)
<input type="submit" value="Search" />
}
<div id="divStudents" style="height: 600px; overflow: auto;"></div>
Note the above assumes you have the following view model
public class StudentSearchVM
{
public string Filter { get; set; }
public SelectList FilterList { get; set; }
}
And that in the GET method that generate this view
StudentSearchVM model = new StudentSearchVM
{
FilterList = new SelectList(new List<string>(){ "All", "Top 3" })
}
return View(model);
Then you would have a single controller method
public ActionResult Filter(string filter)
{
if (filter == "All")
{
List<AspNetUser> model = db.AspNetUsers.ToList();
return PartialView("_Users", model);
}
else
{
....
}
}

How to retrieve Database data from selecting rows

How do I actually retrieve the Primary Key (model.ID) of the selected row from my table. And i want to make same cases if a single row is selected button A B C are enabled but if multiple rows are selected only button c is enabled , a and b will be disabled.
I posted my coding below.
$(document).ready(function () {
var table = $('#LineTables').DataTable();
$('#LineTables tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
});
});
<table id="LineTables" class="display dataTable">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Priority)</th>
<th>#Html.DisplayNameFor(model => model.ProductionOrderNumber)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.ProductGroup.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.ProductName)</th>
<th>#Html.DisplayNameFor(model => model.Quantity)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.Pole)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.Amperage)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.SalesOrderType1.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Market)</th>
<th>#Html.DisplayNameFor(model => model.ProductionOrderStatu.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.SalesOrderNumber)</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Priority)</td>
<td>#Html.DisplayFor(modelItem => item.ProductionOrderNumber)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.ProductGroup.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.ProductName)</td>
<td>#Html.DisplayFor(modelItem => item.Quantity)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.Pole)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.Amperage)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.SalesOrderType1.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Market)</td>
<td>#Html.DisplayFor(modelItem => item.ProductionOrderStatu.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.SalesOrderNumber)</td>
<td>
#Html.ActionLink("New Barcode", "Barcode", new { id = item.ID }, new { #class = "barcode btnic btnicon" })
</td>
</tr>
} </tbody>
</table>
#Html.ActionLink("A", "Index", "A", .......... , new { #class = "btn btn-default btn-ms" })
#Html.ActionLink("B", "Index", "B", .......... , new { #class = "btn btn-default btn-ms" })
#Html.ActionLink("C", "Index", "C", .......... , new { #class = "btn btn-default btn-ms" })
Based comments above:
Firstly you cant use #Html.ActionLink(..) for the 'buttons (these are rendered on the server side and you dont know the selected ID at that point) - use a html <button id="edit">Edit</button>. In the row.click function, test the number of selected rows and enable/disable the buttons as required
var selectedRows = $(this).closest('tbody').children('tr')
.filter('.selected').length;
if (selectedRows = 1) {
// enable edit and details buttons
} else {
// disable edit and details buttons
}
Then in the click events for each button (edit button shown)
$('#edit').click(function() {
var ID = $(this).find('input[type="hidden"]').val(); // as per first answer
window.location.href = '/yourController/edit/' + ID;
return false;
});
The delete button will be a little more complicated - one way would be to loop the selected rows, get the ID and use AJAX to post the ID to your 'Delete' action method, then in the success function, delete the row from your table, for example (not tested)
var url = "#Url.Action("Delete")"; // your delete action
$('#delete').click(function() {
$('#LineTables').children('tbody').children('tr')
.filter('.selected').each(function) {
var row = $(this);
var ID = row.find('input[type="hidden"]').val();
$.post(url, { ID = ID }, function() {
row.remove();
});

Categories