Reputation: 159
Well i m quite new to mvc n i have been one hell of the problem here. I want to pass data from action method using ViewData to my view. I m using Asp.net MVC 2.0 with visual studio 2008.I know how to use view data from an action method & using it in a view.
Here is what i have written in my action method : -
public ActionResult Index()
{
NorthWindEntities db = new NorthWindEntities();
var data = (from id in db.Orders
join ordid in db.Order_Details on id.OrderID equals ordid.OrderID
select new
{
orderid = id.OrderID,
productid = ordid.ProductID,
discount = ordid.Discount
}
);
ViewData["Data"] = data;
return View();
}
and here is the code in the view : -
<%foreach (var item in (IEnumerable)ViewData["Data"] )
{
Response.Write(item.orderId);
} %>
It is giving an error like this..
'object' does not contain a definition for 'orderId' and no extension method 'orderId' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Thanks in advance
Upvotes: 2
Views: 582
Reputation: 9725
Try the following (it's kind of best practice to use a viewmodel... create a class OrderViewModel, then populate that with your select new OrderViewModel like so...
namespace MyApp.ViewModels
{
public class OrderViewModel
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Discount { get; set; }
}
}
public ActionResult Index()
{
NorthWindEntities db = new NorthWindEntities();
List<OrderViewModel> data = (from id in db.Orders
join ordid in db.Order_Details on id.OrderID equals ordid.OrderID
select new OrderViewModel()
{
OrderId = id.OrderID,
ProductId = ordid.ProductID,
Discount = ordid.Discount
}).ToList();
ViewData["Data"] = data;
return View();
and then in your view page...
@using MyApp.ViewModels
<%foreach (var item in (List<OrderViewModel>)ViewData["Data"] )
{
Response.Write(item.orderId);
}%>
Upvotes: 2
Reputation: 11721
You need to take one view model as below :-
public class ViewModelClass
{
public int OrderId{ get; set; }
public int ProductId{ get; set; }
public int Discount{ get; set; }
}
and in controller :-
public ActionResult Index()
{
NorthWindEntities db = new NorthWindEntities();
var data = (from id in db.Orders
join ordid in db.Order_Details on id.OrderID equals ordid.OrderID
select new ViewModelClass
{
orderid = id.OrderID,
productid = ordid.ProductID,
discount = ordid.Discount
}
);
ViewData["Data"] = data;
return View();
}
and in view :-
<%foreach (var item in (ViewData["Data"] as List<ViewModelClass>))
{
Response.Write(item.orderId);
} %>
Upvotes: 1