I have built a 'buy products' page dynamically by building it up for each product. Each product has an 'Add to Basket' button, which are differentiated for each product by having the pID
as the buttons name
attribute. I now want to get the value of the name
attribute within my controller on postback. Not sure how to do this:
View:
@foreach (Ecommerce.Models.HomeModels.Product product in Model)
{
using (Html.BeginForm())
{
@Html.Label(product.Name);
<br />
@Html.Label(product.Description);
<br />
@Html.Label(product.UnitPrice.ToString());
<p></p>
<input name="@product.ID" type="submit" value="Add to Basket" />
}
}
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult BuyProducts(string button)
{
}
If you don't have multiple submit buttons inside a form then there is no need to know on the server side what was the name of the clicked submit button. There are other ways to send back your Id to the server:
Why don't you just generate a hidden field inside your form to hold and post the data?
@foreach (Ecommerce.Models.HomeModels.Product product in Model)
{
using (Html.BeginForm())
{
<input type="hidden" name="productId" value="@product.ID" />
<input type="submit" value="Add to Basket" />
}
}
Then you can get the value of the hidden field in your controller:
public ActionResult BuyProducts(string productId)
{
//..
}