I am trying to figure out a simple basket in which products are stored in a session.
Index Type:
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.product1)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.product1)
</td>
<td>
@Html.ActionLink("Add products to cart", "AddToBasket", new { id=item.id})
</td>
</tr>
}
</table>
Next to each product is "Add to Cart" to the AddToBasket method in the controller, which reads the product identifier and stores it in the session list ["cart"]:
public ActionResult AddToBasket(int? id)
{
if (Session["Basket"] == null)
{
Session["Basket"] = new List<int>();
}
((List<int>)Session["Basket"]).Add(id.Value);
ViewBag.List = Session["Basket"];
return RedirectToAction("Index");
}
Now I saved the product identifiers in the session and would like to get information from the database and match them with the identifiers. And that I can’t understand. I tried to create a dictionary and populate it with values, but obviously this did not work:
public ActionResult ShowBasket()
{
List<int> lista = new List<int>((List<int>)Session["Basket"]);
Dictionary<int, string> productSet = new Dictionary<int, string>();
foreach (var product in lista)
{
productSet[product] = db.products.Find(product).ToString();
}
ViewBag.products = productSet;
return View(slownik);
}
Also tried ADO.Net to retrieve data from the database, but failed again:
public ActionResult ShowBasket()
{
List<int> plist = new List<int>((List<int>)Session["Basket"]);
SqlConnection myConnection = new SqlConnection(my_connection_string);
SqlCommand myCommand;
SqlDataReader myReader;
string s;
myConnection.Open();
s = "select product from db.products where id=" + plist[0];
myCommand = new SqlCommand(s, myConnection);
myReader = myCommand.ExecuteReader();
if (myReader.Read())
{
string loaded_record = myReader.GetString("product1");
}
myConnection.Close();
return View();
}
Can anyone help with this? I am just starting out, after a dozen hours looking for ideas that I decided to ask for help, since I can't handle it ...
!