将值从javascript发送到控制器
本文关键字:控制器 javascript | 更新日期: 2023-09-27 17:51:10
在我们的MVC项目中,我们使用以下javascript函数,我们已经确保这是一个没有任何错误的工作函数。
function GetSelectedItems() {
var newItemIDs = [];
$("#SelectItems tbody").find('tr').each(
function () {
var id = $(this).find('#hfID').val();
var IsAdd = $(this).hasClass('k-state-selected');
if (IsAdd == true) {
newItemIDs.push(id);
}
});
jQuery.ajaxSettings.traditional = true
$.post("/Form8Invoice/AddItemToCart", { NewItemIDs: newItemIDs });
然而,当张贴数组值到控制器,似乎值没有得到适当的传递。控制器动作方法如下,供快速参考。
[HttpPost]
public ActionResult AddItemToCart(string[] newItemIDs, [DataSourceRequest] DataSourceRequest request)
{
if (newItemIDs != null)
{
float grandTotal = 0;
string currentLocation = GetCurrentLocation();
foreach (string itemID in newItemIDs)
{
Location location = new Location();
Stock stock = new Stock();
float UnitPrice = 0;
float SellingPrice = 0;
if(string.IsNullOrEmpty(currentLocation))
{
List<Stock> stokList = _stockRepositoty.GetStocksByItemId(new Guid(itemID)).ToList();
stock = stokList[0];
}
else if (currentLocation != "admin")
{
location = _locationRepository.GetLocationByName(currentLocation);
stock = _stockRepositoty.GetStockByItemIdAndLocation(new Guid(itemID), location.LocationId);
}
else
{
List<Stock> stokList = _stockRepositoty.GetStocksByItemId(new Guid(itemID)).ToList();
stock = stokList[0];
}
if (stock != null)
{
if (!string.IsNullOrEmpty(stock.UnitPrice.ToString()))
{
UnitPrice = float.Parse(stock.UnitPrice.ToString());
SellingPrice = UnitPrice; // + tax - discount
}
}
if (_cartItemsRepository.IsItemAlreadyAdded(GetCurrentLocation(), GetCurrentUser(), new Guid(itemID)))
{
CartItem cartItem = _cartItemsRepository.GetItem(GetCurrentLocation(), GetCurrentUser(), new Guid(itemID));
int Quantity = cartItem.Quantity;
cartItem.Quantity = cartItem.Quantity + 1;
_cartItemsRepository.UpdateItems(cartItem);
float NetAmount = SellingPrice * cartItem.Quantity;
grandTotal = grandTotal + NetAmount;
}
else
{
CartItem cartItem = new CartItem();
cartItem.LocationName = GetCurrentLocation();
cartItem.UserName = GetCurrentUser();
cartItem.ItemId = new Guid(itemID);
cartItem.Quantity = 1;
_cartItemsRepository.InsertItems(cartItem);
float NetAmount = SellingPrice * cartItem.Quantity;
grandTotal = grandTotal + NetAmount;
}
}
ViewBag.GrandTotal = grandTotal.ToString();
_cartItemsRepository.Save();
}
return View();
}
看起来你把parameter属性的大小写写错了。试试这个:
$.post("/Form8Invoice/AddItemToCart", { newItemIDs: newItemIDs });