Reputation: 133
HTML
<div class="fc-option-more-input">
<input type="number" id="itemCount">
<button type="submit" onclick="location.href='@Url.Action("AddToCart", "Controller", new { id = Model[i].ItemID, itemCount = ??? })'" class="button button-add-custom-qty" disabled="disabled">
<span>Add</span>
</button>
</div>
Controller
public ActionResult AddToCart(int id, int itemCount)
{
var ItemToAdd = db.Items
.Single(item => item.ItemID == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
ItemVM model = new ItemVM();
model.ID = ItemToAdd.ItemID;
model.ItemName = ItemToAdd.ItemName;
model.ItemPrice = ItemToAdd.ItemPrice;
model.ImageURL = ItemToAdd.ImageUrl;
model.ItemPrice = ItemToAdd.ItemPrice * itemCount;
cart.AddToCart(model, itemCount);
return RedirectToAction("Index");
}
When button is clicked, I need to somehow read the text input (number) of input element and post it to controller. How can this be achieved ?
Upvotes: 0
Views: 728
Reputation: 810
Or use Form with Razor code, it like this:
<div class="fc-option-more-input">
@using (Html.BeginForm("AddToCart", "Controller", new { id = 0 }, FormMethod.Post))
{
<input type="number" id="itemCount" name="itemCount"/>
<button type="submit"><span>Add</span></button>
}
</div>
Upvotes: 1
Reputation: 133
@using (Html.BeginForm("AddToCart", "ShoppingCart", new { id = Model[i].ItemID}, FormMethod.Post))
{
<div class="fc-option-more-input">
<input type="number" id="itemCount" name="itemCount">
<button type="submit" class="button button-add-custom-qty" disabled="disabled">
<span>Add</span>
</button>
}
</div>
This solved it for me.
Upvotes: 0
Reputation: 131
Why are you not using model to submit your forms with controller side
@model AddToCart
@using (Html.BeginForm("AddToCart", "Controller", FormMethod.Post))
{
@Html.HiddenFor(m => m.Id)
@Html.TextBoxFor(m => m.ItemCount )
<button type="submit"><span>Add</span></button>
}
</div>
public ActionResult AddToCart(AddToCart model)
{
var ItemToAdd = db.Items
.Single(item => item.ItemID == model.Id);
cart.AddToCart(model, model.ItemCount);
return RedirectToAction("Index");
}
public int Id {get;set;}
public int ItemCount {get;set;}
Model is one type of class and if your model is another folder then you can give reference by @using just below @model in cshtml file where Id is your item id and add in your page with hidden so it will be available in model in controller side
Upvotes: 1