I have some data in my Model and Images in Model. Images that are coming From Database and I want to add that image in my Shopping Cart with jquery on click button. I am getting all the data except Images here is the code. Model. Images are the List of string Images and I want one image only in my string images cart class. Help it out.
@{
@model MobileModel
}
<button type="submit" class="addcartbtn mt-5" data-pid="@Model.Id" data-pname="@Model.Name" data-pprice="@Model.Price" data-purl="@Model.Images" data-pqty="1">
<span class=" fa fa-shopping-cart"> Add To Cart</span>
</button>
Jquery Code
$(".addcartbtn").click(function (e) {
e.preventDefault();
var obj = {
"Id": $(this).data("pid"),
"Name": $(this).data("pname"),
"Price": $(this).data("pprice"),
"Images": $(this).data("purl"),
"Quantity": $(this).data("pqty")
}
$(this).parents("#proditem").fadeOut(300);
$.ajax(
{
url: "/Cart/Add",
type: "GET",
data: obj
}
).done(function (itemscount) {
$("#cartitems").text(itemscount);
});
Cart Class
public class ShoppingCartItem
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public string Images { get; set; }
public int Quantity { get; set; }
public int Amount { get {return Quantity * Price;}}
}
Cart Controller where i want to send data
public class CartController : Controller
{
[HttpGet]
public int Add(ShoppingCartItem item)
{
ShoppingCart cart = HttpContext.Session.Get<ShoppingCart>(WebUtil.Cart);
if (cart == null) cart = new ShoppingCart();
cart.Add(item);
HttpContext.Session.Set(WebUtil.Cart, cart);
return cart.NumberOfItems;
}
MobileModel class form where data is comming
public class MobileModel
{
public MobileModel()
{
Images = new List<string>();
}
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public List<string> Images { get; set; }
}
2
Answers
In ShoppingCartItem Model class change
variable to
then in your razor view file get the image like this
It will not save the list of images if you directly pass List data to the button’s attribute, you can
change them to a string by comma to split
.Or you can use
ViewBag
to pass this List of images: