I am using 3 layer architecture for my project. But for an instance i need to return Object from a method and retrieve the values. Here are my two Models:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
}
public class Item
{
public Product Products { get; set; }
public int Quantity { get; set; }
}
and my method is:
public class ProductGateway{
public List<Product> GetProductByProductId(int productId)
{
List<Product> productList = new List<Product>();
SqlConnection connection = new SqlConnection(ConnectionString);
string query = "SELECT ProductName,cast(Price as decimal(10,2)) as Price FROM Product WHERE ProductId='" + productId + "' ";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Product product = new Product();
product.ProductName = reader["ProductName"].ToString();
product.Price = (decimal)reader["Price"];
productList.Add(product);
}
return productList;
}
}
and my Controller:CartController
ProductGateway gateway=new ProductGateway();
public ActionResult BuyProduct( int id)
{
if (Session["cart"]==null)
{
List<Item> cart= new List<Item>();
cart.Add(new Item()
{
Products = gateway.GetProductByProductId(id),// this line getting an error(no list)
Quantity = 1
});
Session["cart"] = cart;
}
And my cshtml view:
@{
var cart = (List<Item>) Session["cart"];
}
@foreach (var item in cart)
{
<tr>
<td class="cart_product">
<a href="@Url.Action("ProductDetails", "Product", new { id = item.Products.ProductId })">@item.Product.Price </a>// an error occurred on ProductId and Price
Now problem is that my return type is List the Controller get an error onProducts = gateway.AllProductsByProductId(id)
and ask for change Item model as Public List<Product> Products
.Thus I want to send Object from GetProductByProductId to avoid error in Cart Controller. Is there any way to solve this issue or i need to change entire codes? I really get confused with this scenario.
My Requirement
1.I need to use product property such as @item.Product.Price
in my cshtml view. (Current Error: Cannot resolve symbol Price
)
2.So that my gateway should return an Product object rather than list of Porduct(for now gateway return list of products).
3. If it is possible to return Object from gateway(assume gateway return single product for each id) then how could I retrieve that object from Cart Controller
Thanks