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>
Related
I'm newbie to AJAX calls and I need to perform simple CRUD operations using AJAX call to Razor Pages. I made a simple function that should delete a row in the table, but it is not working no matter what I try.
Every time I execute the code I get the error message. For first row in the table the error message is:
Error something went wrong with id = 1url:
/Person/Index?handler=DeleteById&id=1
As you can see in commented javascript I tried to use several urls, but none of them worked and I'm getting the same error.
I believe this should be easy, but I'm missing something. Can anyone help me?
Thanks in advance!
My Index.cshtml:
#page
#model WebApplication20.Pages.Person.IndexModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-page="Create">Create New</a>
</p>
<div id="msg"></div>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonName)
</th>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonAddress)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Person)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PersonName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PersonAddress)
</td>
<td>
<button class="btn btn-danger" onclick="DeleteId('#item.PersonId');">Delete</button>
</td>
</tr>
}
</tbody>
</table>
Javascript (embed in <script> tag at bottom of page)
function DeleteId(id) {
var options = {};
//options.url = "/Person/Index?id=" + id + "&handler=DeleteById";
//options.url = "/Index?id=" + id + "&handler=DeleteById";
options.url = "/Person/Index?handler=DeleteById&id=" + id;
options.type = "POST";
options.headers = {
RequestVerificationToken:
$('input:hidden[name="MY-XSRF-TOKEN"]').val()
};
options.success = function (data) {
$("#msg").html("Great Success!");
};
options.error = function () {
$("#msg").html("Error something went wrong with id = " + id + "url: " + options.url);
};
$.ajax(options);
}
and my Index.cshtml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using WebApplication20.Data;
using WebApplication20.Models;
namespace WebApplication20.Pages.Person
{
public class IndexModel : PageModel
{
private readonly WebApplication20.Data.ApplicationDbContext _context;
public IndexModel(WebApplication20.Data.ApplicationDbContext context)
{
_context = context;
}
public IList<Models.Person> Person { get;set; }
public async Task OnGetAsync()
{
Person = await _context.Person.ToListAsync();
}
public IActionResult OnPostDeleteById(int id)
{
var pers = _context.Person.Find(id);
_context.Remove(pers);
_context.SaveChanges();
Person = _context.Person.ToList();
return Page();
}
}
}
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"
})
I'm trying to compare an old value in a <td> with the new value entered by the end user. I'm using ng-blur to detect when there is focus out of the field rather than calling the function. The problem is I can't get this very simple logic to work and I can't figure out why.
This is my table:
<main ng-controller="mainCtrl">
<table class="table table-bordered table-hover" ng-controller="tableCtrl">
<p ng-model="old">{{old}}</p>
<thead>
<th>user name</th>
<th>script name</th>
<th>cron format<span class="glyphicon glyphicon-question-sign" data-toggle="tooltip" data-original-title="Min|Hour|Day Of Month|Month|Day Of Week"></span></th>
</thead>
<tbody ng-repeat="(user_id,script_id) in data">
<tr ng-repeat="(script_id, cron_format) in script_id">
<td class="userName">{{user(user_id)}}</td>
<td class="scriptName">{{script(script_id)}}</td>
<td class="cronFormat"><input type="text" ng-model="cron_format" ng-blur="saveCron(user_id,script_id,cron_format)"/></td>
</tr>
</tbody>
</table>
and this is the comparison :
$scope.old = $scope.cron_format = "";
$scope.saveCron(user_id, script_id, cron_format) {
if ($scope.old == $scope.cron_format) {
return; //value was unchanged
}
$.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function (data) {
alert('cron format changed to:' + cronFormat);
});
$scope.old = $scope.cron_format;
});
Currently, the function executes each time the field is out of focus. What am I missing here?
You can use ng-init for each iteration of the ng-repeat to store the old value, and then use it in the function to compare:
<tr ng-repeat="row in data" ng-init="oldCron = row.cron_format">
And in the function call:
ng-click="saveCron(row.user_id,row.script_id,row.cron_format,oldCron)"
And finally inside the function itself:
$scope.saveCron = function(userId,scriptId,cronFormat,oldCron){
console.log("old cron: " + oldCron);
console.log("new cron: " + cronFormat);
if (oldCron != cronFormat) {
//assign
}
}
Fiddle.
If I understand you correctly, you are trying to save an old value and print it out. You can try changing it to this -
if ($scope.old != $scope.cron_format) {
$.post("updateCronChange.php", "user_id=" + userId + "&script_id=" + scriptId + "&cron_format=" + cronFormat, function(data) {
alert('cron format changed to:' + cronFormat);
});
$scope.old = $scope.cron_format;
}
Here is a working example if you like -
var test = angular.module('test', []);
test.controller('TestCtrl', ['$scope',
function($scope) {
$scope.myModel = '';
$scope.old = '';
$scope.getNewValue = 'false'
$scope.saveModel = function(value) {
if ($scope.old != value) {
$scope.getNewValue = 'true';
$scope.old = value;
$scope.myModel = '';
// Here you can do your post request
} else {
$scope.getNewValue = 'false';
}
};
}
]);
.green {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app='test'>
<div ng-controller="TestCtrl">Enter Some Text
<input type="text" ng-model="myModel" ng-blur="saveModel(myModel)">
<p>Old Value - {{old}}</p>
<p>Current Value - {{myModel}}</p>
<p class="green">Get New Value - {{getNewValue}}</p>
</div>
</div>
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>
The following EditorTemplate does not work how I would like;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.BusinessUnitSelected>" %>
<tr>
<td><%: Model.BusinessUnit.BusinessUnitName %></td>
<td><%: Html.CheckBoxFor(model => model.Selected,
new { onclick = "SaveSelection(" + Model.EmployeeId + ", " + Model.BusinessUnit.BusinessUnitId + ", " + Convert.ToInt32(Model.Selected) + ", " + this.ClientID + ")" }) %>
</td>
</tr>
I want to get the Id of the Checkbox, and this.ClientID fails to do that.
This EditorTemplate forms a grid of rows within a table.
When a person clicks on the checkbox, the SaveSelection javascript is performed;
function SaveSelection(employeeId, businessUnitId, selectedFlag, elementId) {
//var tempFlag = selectedFlag === "0";
var element = document.getElementById(elementId);
if (selectedFlag === null) {
selectedFlag = true;
} else {
selectedFlag = !selectedFlag;
}
var url = '<%: Url.Action("AddBusinessUnitForEmployee", "DataService")%>';
dataService.saveSelection(employeeId, businessUnitId, selectedFlag, elementId, SavedSetting, url);
}
SavedSetting = function(data) {
$('#' + data.ElementId).after('<span class="error">' + data.Message + '</span>');
};
What I want is to display a message next to the checkbox after the server call.
So how do I do this?
Upticks will be awarded for advice on how I can improve this code.
You could use HTML5 data-* attributes:
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.BusinessUnitSelected>"
%>
<tr>
<td><%: Model.BusinessUnit.BusinessUnitName %></td>
<td>
<%= Html.CheckBoxFor(
x => x.Selected,
new {
data_url = Url.Action("AddBusinessUnitForEmployee", "DataService"),
data_employeeId = Model.EmployeeId,
data_businessUnitId = Model.BusinessUnit.BusinessUnitId
}
) %>
</td>
</tr>
and then in a separate javascript file unobtrusively subscribe to the .click() event of those checkboxes and then fetch the required information from the data-* attributes:
$(function() {
$('tr input[type="checkbox"]').click(function() {
var elementId = $(this).attr('id');
var url = $(this).data('url');
var employeeId = $(this).data('employeeId');
var businessUnitId = $(this).data('businessUnitId');
var selectedFlag = !$(this).is(':checked');
dataService.saveSelection(
employeeId,
businessUnitId,
selectedFlag,
elementId,
SavedSetting,
url
);
});
});
Remark: I can't exactly remember if ASP.NET MVC 2 supported the data_ syntax in order to rewrite it to data- syntax in the generated markup. This is defintely supported in ASP.NET MVC 3 and later. If it doesn't work for you, you could use a different overload taking a RouteValueDictionary:
<%= Html.CheckBoxFor(
x => x.Selected,
new RouteValueDictionary
{
{ "data-url", Url.Action("AddBusinessUnitForEmployee", "DataService") },
{ "data-employeeId", Model.EmployeeId },
{ "data-businessUnitId", Model.BusinessUnit.BusinessUnitId }
}
) %>