I am using Asp.Net MVC4 and mongoDB connection. This is my controller :
public ActionResult Delete(string id)
{
var query = from n in ObjectMongoCollection.AsQueryable<User>()
where n.UserId.ToString() == id
select n;
User user = query.FirstOrDefault();
if (user == null)
{
ViewBag.Status = "0";
}
else
{
ObjectMongoCollection.Remove(Query.EQ("_id".ToString(), id));
ViewBag.Status = "1";
}
return View();
And I want to pass this id parameter as the id of selected row of this table :
#foreach (User usr in records)
{
<tr id="#usr.UserId">
<td>
#usr.Name
</td>
<td>
#usr.Surname
</td>
<td>
#usr.Number
</td>
</tr>
}
</tbody>
</table>
<div class="add_delete_toolbar" />
<button id="delete"> Delete</button>
How can I fill this jquery function according to my need:
$('button#delete').click(function () {
...
});
Checking which row is selecting :
$(document).ready(function () {
var table = $('#result').DataTable();
$('#result tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
Thanks a lot.
jQuery DataTable has a plugin called "TableTools" which provides many useful functionalities (including multi-select) and I suggest you to have a look. But to answer your question, try this in you code:
$('button#delete').click(function () {
$("#result tbody tr.selected").each(function() {
$.ajax({
type:"GET",
url: "ToYourController/Delete/" + this.id
})
.success(function() {
alert("succeed!")
})
.error(function() {
alert("failed!");
})
})
}
Related
I have a variable in my jQuery called storedDealer that I want to be filled with the option text when a drop-down item is selected:
var storedDealer = '';
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
});
});
function getDealers(el) {
$.get("#Url.Action("GetDealers", "Admin")?region=" + $(el).val(), function (res) {
var markup = "";
for (var i = 0; i < res.length; i++) {
markup += '<option value='+res[i].Value+'>'+res[i].Text+"</option>"
}
$('#DealerID').prop('disabled', false);
$("#DealerID").html(markup).show();
});
}
My HTML has a little bit of C# Razor code that is the only place the DealerID is defined. I have added the <var id="dealershipName"> item:
<tr>
<td align="right">Dealership:</td>
<td>#Html.DropDownListFor(m => m.DealerID, new List<SelectListItem>())</td>
<td><var id="dealershipName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
I would not have thought the Razor variables would be visible by jQuery, but they somehow seem to work.
But when the search is submitted, the page refreshes. Now the drop-down list is reset and the <var> field is blank.
That <var> field is what I added, and I am trying to get to work.
How can I get the value to stay after the form reloads?
I think you can try to use Session,here is a demo for .net6.Each time the slected value is changed,change storedDealer and the session data.And when you refresh the page,if the session data is not null,storedDealer will be set with the session data:
Program.cs:
builder.Services.AddControllersWithViews();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
actions:
public IActionResult Test(){
return View();
}
public void SetSession(string storedDealer) {
HttpContext.Session.SetString("storedDealer", storedDealer);
}
Test view:
var storedDealer = "";
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
if(storedDealer==""&&"#(string.IsNullOrEmpty(Context.Session.GetString("storedDealer")))"!=True)
{
storedDealer = "#Context.Session.GetString("storedDealer")";
}
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
$.ajax({
type: "GET",
url: "SetSession",
data: {storedDealer:$("#IdSelectIdEmpleado").val()},
});
});
});
I have a simple table. When a user clicks on a row, a jscript gets triggered. How can I get a value from row/cell to use in jscript to check true or false please? There is also a seperate click-row script but ignore that for now.
<tbody>
#if (Model != null)
{
foreach (CELIntranet.Models.tblReportsList item in Model)
{
<tr class="clickable-row" id="myid" data-mydata1=UserPermission href="#Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
<td>#Html.Raw(item.ReportNumber)</td>
<td>#Html.Raw(item.ReportName)</td>
<td>#Html.Raw(item.ReportGroup)</td>
<td>#Html.Raw(item.ReportStatus)</td>
#if (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))
{
<td style="color:dodgerblue">Granted</td>
}
else
{
<td style="color:orangered">Restricted</td>
}
</tr>
}
}
</tbody>
<script type="text/javascript">
$(function () {
var ClickedTableRowCellValue = ("Need some code to get UserPermission value from the clicked row");
$('table > tbody > tr').click(function () {
if (ClickedTableRowCellValue == True) {
alert("Granted");
Popup();
}
alert("Restricted");
});
});
</script>
// Click row ignore this code for now!
#section Scripts {
<script type="text/javascript">
var clicker = new TableCliker();
$(document).ready(function () {
clicker.Initialise();
//alert("Test");
//Popup();
});
</script>
Try to change your html like this:
<tr class="clickable-row" id="myid" onclick="test(this)" UserPermission = "#(User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))" data-mydata1=UserPermission href="#Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
So that you can add UserPermission attribute to <tr></tr>.Here is the js:
function test(t){
var ClickedTableRowCellValue = $(t).attr("UserPermission").
if (ClickedTableRowCellValue == True) {
alert("Granted");
Popup();
}
alert("Restricted");
}
Since the click() event returns the exact element that was clicked you can simply use this (the element that is clicked). And get the attribute UserPermission.
$('tr').click(function () {
var authorized = $(this).attr("UserPermission");
if (authorized) { // you don't need to state == true since it will compare to true by default
alert("Granted");
Popup();
}
alert("Restricted");
});
My group and I have been struggling to find an answer to this for our website and we've finally taken the step to asking the community for some help!
The goal is the try and link the button of our website to "remove from cart" and set the database back to 0 as well as refresh the page and show the decrementation taking place.
The shopping cart view's javascript does not seem to be working, but I'm not sure if this is ultimately the issue. We've followed many guides such as the MVC music store and ASP.NET documentations.
Index.cshtml:
script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
function handleUpdate() {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
</script>
<h3>
<em>Review</em> your cart:
</h3>
<div id="update-message">
</div>
<div style="height:600px; overflow:auto; padding-top: 50px; margin-left: 200px; width: 1050px; ">
<table id="cart-summary" border="1" frame="void" rules="rows" style="width:100%;margin-left:auto; margin-right: auto;">
<tr class="data-table">
<th colspan="1">
Item(s)
</th>
<th colspan="1" style="text-align:center;">
Price
</th>
<th colspan="1" style="text-align:center;">
Quantity
</th>
<th colspan="1" style="text-align:center;">
Total
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItem)
{
<tr>
<td style="margin:auto;width:500px;">
<div style="float:left;">
<a href=#Url.Content(String.Format("~/Books/Details/{0}", item.Book.id))>
<img class="img-responsive" src="#Url.Content(String.Format("~/Content/img/books/{0}.jpg",item.Book.ISBN))" style="width: 100px; height: 150px;" />
</a>
</div>
<div style="margin-top:37px;">
<a href=#Url.Content(String.Format("~/Books/Details/{0}", item.Book.id))>
<span>#Html.DisplayFor(modelItem => item.Book.Title)</span><br />
</a>
<span style="text-align:left;">#Html.DisplayFor(modelItem => item.Book.Author)</span><br /><br />
<span style="text-align:left">ISBN: #Html.DisplayFor(modelItem => item.Book.ISBN)</span>
</div>
</td>
<td>
<p style="text-align:center;">#item.Book.PriceNew</p>
</td>
<td>
<p style="text-align:center;">#item.Quantity</p>
Remove from cart
<!--data-url='Url.Content("~/ShoppingCart/RemoveFromCart")'>
Remove from cart
</a>-->
</td>
<td>
<p>#Model.CartTotal</p>
</td>
</tr>
}
<tr>
<td></td>
<td>
<p style="padding-top:15px;"></p>
<br />
<button type="button">
#Html.ActionLink("Back to List", "../Books/Index")
</button>
</td>
<td></td>
<td id="cart-total">
<p style="padding-top: 10px;font-weight:bold;color:rgb(179,0,0);font-size:18px;">Subtotal: #Model.CartTotal</p>
<button type="button">
#Html.ActionLink("Checkout!", "AddressAndPayment", "Checkout")
</button>
</td>
</tr>
</table>
</div>
The next set of code is the C# code.
Cart.cs:
public int RemoveFromCart(int id)
{
var cartItem = bookDb.Carts.Single(
c => (c.CartId == ShoppingCartId)
&& c.RecordId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantity > 1)
{
cartItem.Quantity--;
itemCount = cartItem.Quantity;
}
else
{
bookDb.Carts.Remove(cartItem);
}
bookDb.SaveChanges();
}
return itemCount;
}
Finally to complete the MVC set of code which relate to each other...We also believe there may be an error here. Again, we just aren't experienced enough to know.
ShoppingCartController.cs:
// GET: ShoppingCart
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our View Model
var viewModel = new ShoppingCartViewModel
{
CartItem = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
return View(viewModel);
}
// GET: Book/Details/5
// Button that allows you to add to the cart you will be redirected to the Shopping cart index page
public ActionResult AddToCart(string id)
{
var addedBook = bookdb.Books.Single(book => book.ISBN == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedBook);
bookdb.SaveChanges();
return RedirectToAction("Index");
}
// this is attached to the remove to cart button in the shopping cart index page, the index page will then reload
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the book to display confirmation
string bookName = bookdb.Carts.Single(book => book.RecordId == id).Book.Title;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(bookName) + " has been removed from the shopping cart",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
//return view();
return Json(results);
}
Thanks a bunch!
Index.cshtml
<script>
$(document).on('click', '.del-CartDetail', function () {
var id = $(this).data("id");
$("#hdnCartDetailId").val(id);
$("#modal-del-cartdetail").modal({
backdrop: 'static',
keyboard: false,
show: true
});
});
$("#btnModalSubmit").click(function () {
var buttonText = $("#btnModalSubmit").html();
$("#btnModalSubmit").attr('disabled', '').html('<i class="fa fa-spinner fa-spin"></i> ' + buttonText);
var id = $("#hdnCartDetailId").val();
$.ajax({
url: '/CartDetail/DeleteCartDetail',
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Id: id }),
success: function (result) {
debugger;
if (result.success) {
$('#modal-del-cartdetail .close').click();
//Page redirect after delete record
window.location.reload();
$('#modal-del-cartdetail').show();
INTAPP.Util.Notification(true, "Selected Cart(s) have been successfully deleted.");
} else {
INTAPP.Util.HandleLogout(data.message);
INTAPP.Util.Notification(false, "Some error occured while deleting selected Cart.");
}
$("#btnModalSubmit").attr('disabled', null).html('Submit');
},
error: function (xhr, status, error) {
INTAPP.Util.Notification(false, error);
$("#btnModalSubmit").attr('disabled', null).html('Submit');
}
});
});
</script>
#Html.Partial("ConfirmModal", new ModalViewModel
{
Id = "modal-del-cartdetail",
IsAlertModel = false,
Title = "Delete Product",
Message = "Are you sure you want to delete the cart detail?",
HiddenElementId = "hdnCartDetailId"
})
can you please tell me why my row is not deleted.I I make a demo in which I added the student name .I am able to add the student name .Now I have two issue I am not able to delete row and Edit.can you please tell where i am wrong ?
here is my demo
http://plnkr.co/edit/1lem6t4h7b6Eefsz32t6?p=preview
app.controller("studentcntr",['$scope',function(scope){
scope.studentDetail=[];
scope.addStudent=function(){
bootbox.prompt("Enter Name!",function(res){
console.log(res);
if(res==null){
}else {
scope.studentDetail.push({ name: res });
}
scope.$digest();
});
};
scope.editRowName=function (name) {
// body...
// alert(name);
setTimeout(function() {
$('.bootbox-input').val(name);
}, 10);
}
scope.deleteRow=function (id) {
// body...
alert('s'+id)
$('#'+id).remove();
}
}])
I am able to delete row .But problem is that when I remove row and add new name it create again delete row why ? why it is now delete permanently
why it is now delete permanently
As you are not deleting it from scope.studentDetail it is persisting.
Changes
HTML
<td ><button ng-click="editRowName(student)">Edit</button></td>
<td ><button ng-click="deleteRow($index)" >Delete</button></td>
Script
scope.editRowName=function (student) {
bootbox.prompt({
title: "What is your name?", //Title
value: student.name, //Pre-filled name
callback: function(result) {
student.name = result; //Update name
scope.$digest();
}
});
}
scope.deleteRow=function ($index) {
scope.studentDetail.splice($index, 1);
}
DEMO
The problem was that you were removing the element from DOM and not from the data model..
http://plnkr.co/edit/a4WLy1ckQHT68uz1CGeh?p=preview
It works for both edit and delete.
<td><button ng-click="editRowName($index, student.name)">Edit</button></td>
<td><button ng-click="deleteRow($index)" >Delete</button></td>
and in the controller
scope.editRowName=function (index, name) {
scope.currentIndex = index;
bootbox.prompt("Enter New name for " + name,function(res){
console.log(res);
if(res==null){
}else {
if (scope.currentIndex === -1) {
scope.studentDetail.push({ name: res });
} else {
scope.studentDetail[scope.currentIndex].name = res;
scope.currentIndex = -1;
}
}
scope.$digest();
});
}
scope.deleteRow=function (id) {
scope.studentDetail.splice(id, 1);
}
I will like to request your help to debug my Jquery which seems not to pick-up my new count for the quantity.
I am in my application and I added a product,
I changed the quantity of the item from 1 to 3. I clicked the refresh button.
I was expecting the total will be changed (total X 3) instead of (total X 1)
I think the problem is coming from the cartCount variable. this variable doesn't seems
to get the new count of the #html.TextBoxFor field from the view.
I got an error with the javascript RefreshQuantity :
In Chrome Pf12, in the header tab
I can see
header tab
id:320
cartCount:0
The id 320 is the corresponding id in the Panier table.
Preview tab
{Message: Error occured or invalid input...,CartTotal:-1, ItemCount:-1, DeleteId:210}
CartCount: -1
CartTotal: -1
DeleteId: 320
ItemCount: -1
Message: "Error occurred or invalid input..."
Response Tab
{"Message":"Error occurred or invalid
input...","CartTotal":-1,"CartCount":-1,"ItemCount":-1,"DeleteId":320}
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
#using (Html.BeginForm())
{
<h3>
<em>Visualisation </em> du panier:
#if (TempData["err_message"] != null)
{
#TempData["err_message"]
}
</h3>
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '#Url.Action("RemoveFromCart","Panier")',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).remove();
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
$.get('#Url.Action("CartSummary", "Panier")');
$('#content').html(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
});
$(function () {
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = 0;
if ($("#" + $(this).attr("id")).val() !== '') {
countToUpdate = $("#" + $(this).attr("id")).val();
}
if (recordToUpdate != '') {
// Perform the ajax post
$.post("/Panier/UpdateCartCount", { "id": recordToUpdate, "cartCount":
countToUpdate },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data. DeleteId).fadeOut('slow');
}
$('#update-message').text(htmlDecode(data.Message));
$('#cart-total').text(data.CartTotal);
$('#cart-status').text('Cart (' + data.CartCount + ')');
//Only process the callback data when no server error occurs
if (data.ItemCount != -1) {
$('#cart-total').text(data.CartTotal);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
}
);
}
});
});
$(function () {
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
}
}
});
function clearUpdateMessage() {
// Reset update-message area
$('#update-message').text('');
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
}
else {
return '';
}
}
</script>
<div>
#for (int i = 0; i < Model.CartItems.Count; i++)
{
<p>
#Html.ValidationMessageFor(model => model.CartItems[i].Quantite)
</p>
}
</div>
<div id="update-message">
</div>
<div id="content">
#if (Model.CartTotal != 0)
{
<p class="button">
#Html.ActionLink("Paiement >>", "AddressAndPayment", "Checkout")
</p>
<p class="NouvelAjout">
#Html.ActionLink("Ajouter un autre article >>", "Magasin", "Home")
</p>
}
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#{int ix = 0;}
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td>
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();"
})
</td>
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Count">Refresh quantity</a> | />a
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.PanierId"> Enlever du panier
>> </a>
</td>
</tr>
ix++;
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
</div>
}
Do we have anyway to debug the javascript from Visual Studio? I saw a post which is stating it was a problem with Visual studio ref.: Visual Studio 2013 can't debug javascript in cshtml
ShoppingCart.cs
public int UpdateCartCount(int id, int cartCount)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.PanierId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartCount > 0) <=== cartCount is always 0 it should contains the new value
added from the view.
{
cartItem.Quantite = cartCount;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
}
I need to know how to extract the new value added by the user in the screen from the view field
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();"
})
Change to textbox:
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();",
#class="new-count"
})
Change to script:
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = $(this)
.closest('tr')
.find('.new-count').val();
The error was on the Index.cshtml with the var id="CartItems_#(ix)__Count"
old view
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Count">Refresh quantity</a> | />a
</td>
Modified
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Quantite">Refresh quantity</a> | />a
</td>