Jelo Melo
Jelo Melo

Reputation: 52

How to get ID of the currently viewing Product in asp.net mvc?

I have a list of products(images) which users can scroll(I do it using Jquery) & their is id associated with each image, I want if user click on the button(add to cart) then the product should be add to the cart. I don't know how to get the ID of currently displaying product. Please help i am new to MVC.

View

@using (Html.BeginForm("Index","Product"))
{
    <input type=submit value="Add To Cart"/>
}

Controller

 [HttpPost]
    public ActionResult Index(MyUsers user)
    {
        string s = user.Name;
        return View();
    }

Upvotes: 0

Views: 1157

Answers (2)

karaxuna
karaxuna

Reputation: 26930

View:

@using (Html.BeginForm()) 
{ 
    foreach(Product product in Model)
    {
        @Html.LabelFor(model => product.Name)
        @Html.ActionLink("Add To Cart", "Add", "Product", new { id = product.Id })
    }
}

Controller:

public ActionResult Add(int id)   
{   
    // Your code...   
} 

Upvotes: 0

Juraj Such&#225;r
Juraj Such&#225;r

Reputation: 1117

If there is a button "Add to chart" associated with each product, add a hidden field with appropriate product ID next to each of these buttons.

@using (Html.BeginForm("Index","Product"))
{
    @Html.Hidden("ProductID", productID)
    <input type="submit" value="Add To Cart"/>
}

Then add parameter ProductID to the action method.

[HttpPost]
public ActionResult Index(MyUsers user, int productID)
{
    // Your code...
}

Upvotes: 1

Related Questions