![](/img/trans.png)
[英]Get drop down list default selected item is not passing to the controller in Asp.net MVC
[英]MVC 5 drop down list value not passing into controller
我在“產品詳細信息”視圖中創建了一個dropdownlistfor,它具有5個硬編碼值(1、2、3、4、5),當我選擇該值時,我希望將其傳遞到ShoppingCart控制器中的AddToCartWithQuantity方法中,然后,當我單擊“添加到購物車”按鈕時,使用相同名稱的購物車模型方法,但是當我將商品添加到購物車時,數量變為0。
我的產品詳細信息視圖:
@model BigVisionGames.Models.Products
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Product: @Model.ProductName</h3>
<div id="product-details">
<p>
<em>Price: </em>
£@($"{Model.Price:F}")
</p>
<div style="color:black">
@Html.DropDownListFor(model => model.ChosenQuantity, new
List<SelectListItem>
{
new SelectListItem{ Text="1", Value = "1" },
new SelectListItem{ Text="2", Value = "2" },
new SelectListItem{ Text="3", Value = "3" },
new SelectListItem{ Text="4", Value = "4" },
new SelectListItem{ Text="5", Value = "5" }
})
@Html.ValidationMessageFor(model => model.ChosenQuantity, "", new { @class = "text-danger" })
</div>
@if (Model.StockLevel == 0)
{
<p style="color:red">This item is currently out of stock!</p>
}
else
{
<p class="btn">
@Html.ActionLink("Add to cart", "AddToCartWithQuantity", "ShoppingCart", new { id = Model.Id}, "")
</p>
}
ShoppingCartController方法
public ActionResult AddToCartWithQuantity(int id, Products productModel)
{
// Retrieve the product from the database
var addedproduct = storeDB.Products
.Single(product => product.Id == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCartWithQuantity(addedproduct, productModel.ChosenQuantity);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
用於設置所選數量的ShoppingCart Model方法
public void AddToCartWithQuantity(Products product, int chosenQuantity)
{
// Get the matching cart and product instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ProductId == product.Id);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
ProductId = product.Id,
CartId = ShoppingCartId,
Quantity = chosenQuantity,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart,
// then add one to the quantity
cartItem.Quantity++;
}
// Save changes
storeDB.SaveChanges();
}
您當前的代碼正在呈現一個錨標記,然后單擊該標記將執行帶有查詢字符串中ID的GET請求。 如果要從數量下拉列表中發送所選值,則需要讀取並發送它。
首先更新要在其中呈現鏈接的代碼,以便它將為a
標簽創建一個Id
屬性,我們稍后可以在javascript中使用它來覆蓋默認的點擊行為。
@Html.ActionLink("Add to cart", "AddToCartWithQuantity", "ShoppingCart",
new { id = Model.Id },new { id = "addToCart" } )
這將呈現ID為addToCart
的錨標記
現在,您可以使用一些JavaScript來偵聽此錨標記上的click事件,阻止默認行為(導航到目標url)並發送所需的數據。 這是做一個ajax發布的例子
$(function (){
$("#addToCart").click(function (e){
e.preventDefault();
var url = $(this).attr("href");
url = url + '?chosenQuantity=' + $("#ChosenQuantity").val();
$.post(url).done(function (res){
if (res.status === "success")
{
//update cart UI
alert(res.cartItemCount);
}
});
});
});
現在,由於我們正在執行ajax提交,讓我們返回一個帶有status和cartItemCount
屬性的JSON響應。 我們的js代碼正在對此進行檢查,以查看ajax調用done
事件中的操作是否成功。 另外,由於我們僅需要ID和數量,因此您無需將Product
實體用作參數。 對Id
使用簡單的int
類型
[HttpPost]
public ActionResult AddToCartWithQuantity(int id, int chosenQuantity)
{
// Your existing code to save. Use id to get the product
// to do :replace the hard coded 1 with actual value from db
return Json(new { status = "success", cartItemCount = 1 });
}
另一種選擇是進行表單提交。 在這種情況下,將您的SELECT和鏈接包裝在一個form元素內(其操作設置為/ShoppingCart/AddToCartWithQuantity
),並在單擊鏈接時提交一個表單。
<form action='@Url.Action("AddToCartWithQuantity","ShoppingCart")' method='post'>
<!-- SELECT and Link goes here-->
</form>
腳本將是
$(function (){
$("#addToCart").click(function (e){
e.preventDefault();
$(this).closest("form").submit();
});
});
由於我們的代碼正在執行完整的表單提交,因此請確保您的操作方法返回了重定向結果。
[HttpPost]
public ActionResult AddToCartWithQuantity(NewProjectModel product, int chosenQuantity)
{
// Your existing code to save
return RedirectToAction("Index","ShoppingCart");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.