ASP.NET MVC -- Remove From Shopping Cart - javascript

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"
})

Related

Adding an Item from a string to insert into the database table

I am trying to add an item from a string to insert into a table along with the other information. I have followed a tutorial for a shopping cart and I am in need of adding the total cost to the record. I have the item in the array and have added what I believe to be the items I need. What I am having an issue with is implementing it in the controller side of the project. Below is the code I have, I am not 100% sure if what I added for the total price is correct. This should be in decimal form. thank for your help.
Shopping Cart CSHTML page. This is not the whole page just relevant parts.
using (Html.BeginForm("AddOrder", "Parts", new { id = "f" }))
{
<table id="tableOrder" class="table table-hover">
<tr>
<th>Part Number</th>
<th>Unit Price</th>
<th>Qty Selected</th>
<th>Description</th>
<th>Total Price</th>
</tr>
#foreach (var parts in Model)
{
<tr>
<td>#parts.Material</td>
<td>#string.Format("{0:C2}", parts.SellingPrice)</td>
<td>#parts.QtySelected</td>
<td>#parts.Description</td>
<td>#string.Format("{0:C2}", (parts.SellingPrice * parts.QtySelected))</td>
</tr>
totalOrder += (parts.QtySelected * parts.SellingPrice);
#Html.HiddenFor(p => parts.Material)
#Html.HiddenFor(p => parts.QtySelected)
}
</table>
<!-- TOTAL PRICE-->
<h4 style="margin-left: 66%;">Total : <span class="label label-info">#string.Format("{0:C2}", totalOrder)</span></h4>
#Html.HiddenFor(p => totalOrder)
<div class="modal-footer">
<button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="SaveOrder" data-toggle="modal" data-target="#additionalInfo">Save Order</button>
</div> <!-- MODAL FOOTER-->
}
Java Script portion.
$("#SaveOrder").click(function () {
var $form = $(this).closest('form');
var dataPart = $form.serializeArray();
console.log(dataPart);
var arrIdPart = [];
var arrQtyPart = [];
var totalPrice = [];
for (i = 0; i < dataPart.length; i++)
{
if (dataPart[i].name == 'parts.Material')
{
arrIdPart.push(dataPart[i].value);
}
else if (dataPart[i].name == 'parts.QtySelected')
{
arrQtyPart.push(dataPart[i].value);
}
else if (dataPart[i].name == 'totalOrder')
{
totalPrice.push(dataPart[i].value);
}
}
$.ajax({
type: 'POST',
url: '#Url.Action("AddOrder", "Parts")',
data: { arrIdPart, arrQtyPart },
success: function (response) {
if(response.data == true)
{
alert("Order has saved successfully ");
}
else
{
alert("Order did not save successfully ! ");
}
},
error: function (error) {
alert("Order did not collect data successfully ! ");
}
});
});
Here is the controller action. I have added the parts to all of these that have to do with totalPrice. The issue is how to implement it in the record add to customer.
[HttpPost]
public ActionResult AddOrder(string[] arrIdPart, int[] arrQtyPart, decimal[] totalPrice)
{
int countPart = arrIdPart.Length;
int CompanyId = (int)Session["CompanyId"];
bool statusTran = false;
EDIT - added
decimal totPrice = totalPrice.Length;
CustomerEntities _context = new CustomerEntities();
using (DbContextTransaction dbTran = _context.Database.BeginTransaction())
{
try
{
CompanyNames customer = _context.CompanyNames.Find(CompanyId);
if (customer != null)
{
EDIT - Changed this
customer.Ordered.Add(new Orders { OrderDate = DateTime.Now, TotalPrice = totPrice });
}
Orders orderSelected = customer.Ordered.LastOrDefault();
if (orderSelected != null)
{
for (int i = 0; i < countPart; i++)
{
Parts selectedPart = _context.Parts.Find(arrIdPart[i]);
orderSelected.OrderDetail.Add(new OrderDetails { Parts = selectedPart, Quantity = arrQtyPart[i] });
}
}
//Save Changes
int countResult = _context.SaveChanges();
//Commit Transaction
dbTran.Commit();
if (countPart > 0)
{
statusTran = true;
partsList.Clear();
}
}
catch (Exception)
{
dbTran.Rollback();
}
}
return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);
}
}
However I am not getting anything for totalOrder in the script. Says its null. But in my 'console.log(dataPart);' In the console it is there with the name totalOrder.
Not saying it's the final answer but I can't put multiline code in a comment..
I wish to point out that you don't post the total price you calculated, to the server:
type: 'POST',
url: '#Url.Action("AddOrder", "Parts")',
data: { arrIdPart, arrQtyPart }, //look, no totalprice data? You did all those efforts to calc it and then did nothing with it?
success: function (response) {
if(response.data == true)
totalPrice should probably be called arrSubtotalPart by the way, for consistency..
Warning: The server receives the items and the quantities, it should work the price out from that rather than let the end user dictate how much he wants to pay for an order by manipulating the JavaScript

Getting error when reloading page in jquery success call in mvc4 jquery

I have view called detailsbyClientId.cshtml which displays table data(data binded through model) and some buttons. When i click on button i am calling actionmethod and i will do some calculations in controller(i will process some rows of data).
Below is jquery code.
My button
Jquery Code.
function batchSave()
{
$(document).ready(function(){
var clientId = #Html.Raw(Json.Encode(Model.detailsbyclientId[0].clientId));
var ids = #Html.Raw(Json.Encode(Model.Ids));
var arr = jQuery.makeArray(ids);
$.ajax({
type: 'POST',
data: { 'clientId':clientId,'uploadidList': arr.join()},
dataType: 'json',
url: '/documentVerification/batchSave',
success: function (data) {
fun_toastr_notify('success', 'Document have been Approved');
$("#dialog").dialog("close");
$('#dialog-form').dialog('close');
}
, error: function (error) {
fun_toastr_notify('error', data, 'Error');
}
});
});
}
This is my controller code.
public JsonResult batchSave(int? clientId, int? currentFilter, int? page,string uploadidList)
{
documentVerificationBAL objBAL = new documentVerificationBAL();
int[] myuploadId = uploadidList.Split(',').Select(int.Parse).ToArray();
foreach(var indId in myuploadId)
{
int latupdateVersion= objBAL.getlatestVersion(indId);
if(latupdateVersion>1)
{
List<uploadanddocContent> uploadanddocContent = objBAL.metadataexternalUsers(indId, latupdateVersion);
foreach(var data in uploadanddocContent)
{
int Status = UploadDocument.SaveUploadContent(data.upld_Value, data.upld_Label, indId, data.doc_contentId);
if(Status==1)
{
int latStatus = objBAL.updateMasterTable(indId);
}
}
}
}
if (clientId != null)
{
page = 1;
}
else
{
clientId = currentFilter;
}
ViewBag.CurrentFilter = clientId;
int pageSize = 8;
int pageNumber = (page ?? 1);
int cId = Convert.ToInt32(clientId);
List<detailsbyClientId> detailsbyclient = objBAL.detailsbyclient(cId);
IPagedList<detailsbyClientId> pagedLog = detailsbyclient.ToPagedList(pageNumber, pageSize);
detailsbyclientIdviewModel model;
model = new detailsbyclientIdviewModel()
{
detailsbyclientId = pagedLog,
Ids = pagedLog.Select(x => x.upld_Id)
};
return Json(1, JsonRequestBehavior.AllowGet);
//return View("detailsbyClientId", model);
}
Inside batchSave action method i will do some calculation so that next time some rows should not display after clicking on button. My view is not getting updated because i am not handling anything in success call. So can someone suggest me how can i achieve this? thank you. I tried with location.reload but in the below line i am getting error var clientId = #Html.Raw(Json.Encode(Model.detailsbyclientId[0].clientId));
View page
#if (Model.detailsbyclientId != null)
{
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
<th>Corporate Name</th>
<th>employee ID</th>
<th>employee Name</th>
<th>Nationality</th>
<th>Document Type</th>
<th>Actions</th>
</tr>
#foreach (var group in Model.detailsbyclientId)
{
<tr>
<td> #group.clientName </td>
<td> #group.employeeId </td>
<td> #group.employeeName </td>
<td>#group.Nationality</td>
<td> #group.documentType </td>
<td scope="col">
<input type="button" class="btn btn-primary btn-cons" value="View Document" onclick="showDocumentData('#group.upld_Id');" />
</td>
<td></td>
</tr>
}
<tr>
<td></td>
<td scope="col">
<input type="button" class="btn btn-primary btn-cons" value="Done" onclick="batchSave();" />
<input type="button" class="btn btn-primary btn-cons" value="Cancel" onclick="batchCancel();" />
</td>
</tr>
</table>
#Html.PagedListPager(Model.detailsbyclientId, page => Url.Action("detailsbyClientId",
new { page, currentFilter = ViewBag.CurrentFilter, pageSize = 5 }))
Page #(Model.detailsbyclientId.PageCount < Model.detailsbyclientId.PageNumber ? 0 : Model.detailsbyclientId.PageNumber) of #Model.detailsbyclientId.PageCount
</div>
}
else
{
<div>No records found</div>
}

How to use row id in controller in ap.net mvc

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!");
})
})
}

Javascript value not beeing extracted from the #html.TextBoxFor in a view

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>

Html.Textbox value is not passing in url using javascript

I`m trying to pass the Html.Textbox value in the javascript url but it is giving an error.
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /WebProduct/Add/1
Below is my view class. from which i`m passing values to my controller.
Edited
#model IEnumerable<DatabaseService_WebAPI.Models.ProductType>
#{
ViewBag.Title = "Tablets";
<script type="text/javascript">
$(function () {
$('#edit').click(function () {
var name = $('#quantity').val();
this.href = this.href + '&quantity=' + encodeURIComponent(name);
});
});
</script>
}
<h2>Tablets</h2>
#using (Html.BeginForm("Add", "WebProduct", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.Batch)
</th>
<th>
#Html.DisplayNameFor(model => model.Expiry)
</th>
<th>
#Html.DisplayNameFor(model => model.Quantity)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Batch)
</td>
<td>
#Html.DisplayFor(modelItem => item.Expiry)
</td>
<td>
#Html.TextBox("quantity")
</td>
<td>
#Html.ActionLink("Add", "Add", new { name = item.Name, type = item.Type }, new { id = "edit" })
</td>
</tr>
}
</table>
}
<div>
#Html.ActionLink("Back to List", "Create")
</div>
And its my controller method in which I`m passing the values.
[HttpPost]
public ActionResult Add(string quantity, string name, string type)
{
Product product = new Product();
if (type=="Tablet")
{
//string order = type.Name + " " + type.Quantity;
LocalDB tobj = ldb.LocalDBs.Single(s => s.User == User.Identity.Name);
product.city = tobj.City;
product.OrderDate = DateTime.Now.Date.ToShortDateString();
product.ShopName = tobj.ShopName;
product.User = tobj.User;
//product.OrderDetail = order;
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("TypeT", "WebProduct");
}
else if (type == "Syrup")
{
//string order = type.Name + " " + type.Quantity;
LocalDB tobj = ldb.LocalDBs.Single(s => s.User == User.Identity.Name);
product.city = tobj.City;
product.OrderDate = DateTime.Now.Date.ToShortDateString();
product.ShopName = tobj.ShopName;
product.User = tobj.User;
// product.OrderDetail = order;
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("TypeS", "WebProduct");
}
else
{
// string order = type.Name + " " + type.Quantity;
LocalDB tobj = ldb.LocalDBs.Single(s => s.User == User.Identity.Name);
product.city = tobj.City;
product.OrderDate = DateTime.Now.Date.ToShortDateString();
product.ShopName = tobj.ShopName;
product.User = tobj.User;
// product.OrderDetail = order;
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("TypeC", "WebProduct");
}
return View();
}
At this point i don't want to use button options. because i want to send database record and user's input to my controller`s method.
My understanding is that your
this.href == localhost:3325/WebProduct/Add?name=Panadol&type=Tablet
if that is correct then the following should work
$(function ()
{
$('#edit').click(function ()
{
var name = $('#quantity').val();
var href = this.href;
var splitHalfUrl = href.split('?');
var splitQueryString = splitHalfUrl[1].split('&');
window.location = "/WebProduct/Add?" + "quantity=" + encodeURIComponent(name) // Quantity
"&" + splitQueryString[0] + // Name
"&" + splitQueryString[1]; // Type
});
});
Ok couple things I'd like to point out, you need to prevent default behavior on the ActionLink:
<script type="text/javascript">
$(function () {
$('#edit').click(function(event) {
event.preventDefault();
var name = $('#quantity').val();
window.location = this.href + '&quantity=' + encodeURIComponent(name);
});
});
</script>
That should redirect your page to the url that you want: localhost:port/WebProduct/Add?name=Name&type=Type&quantity=Quantity
If you get another error, please check if your controller action is setup properly (spelling mistake can be a bitch).
The line
this.href = this.href + '?quantity=' + encodeURIComponent(name);
your url will read something like
http://localhost:54745/WebProduct/Add?id=1&name=myname&type=mytype?quantity=4
two question marks can't be in the same url query string like this
UPDATE:
Your also in a foreach loop, meaning you will have multiple textboxes with id 'quantity' and multiple add links with id 'edit'
UPDATE 2:
add the parameter 'e' on the click event in order to call 'e.preventDefault()' this will stop the link from going to its URL.
then you will also need to set the window.location, rather than this.href (which is the link URL)
$(function () {
$('#edit').click(function (e) {
e.preventDefault();
var name = $('#quantity').val();
window.location = this.href + '&quantity=' + encodeURIComponent(name);
});
});
</script>

Categories

Resources