我长期以来一直坚持这个问题并且会喜欢一些帮助。
在视图中,人们可以从两个radiobutton列表中选择两个项目,这两个项目通过FormMethod.Get返回到HomeController中的Index事件。
查询这两个值'parts和'use'以返回结果,并通过viewbag将其传递回视图。然而,viewbag在视图中返回{Item = Kona,Price = 400.0000,Quantity = 2}这样的行。
虽然我想返回item.Item,Item.Price等每个项目,但我可以单独使用它们。
我已经尝试了一切我无法找到的东西。 匿名类项也会抛出红色错误
查看
foreach(var item in ViewBag.getstock)
{ //Show it and then make a new line with the <BR/>
@item < br / >
//{ Item = Kona, Price = 400.0000, Quantity = 2 }
}
的HomeController
public ActionResult Index()
{
//this returns the entire query string
ViewBag.querystring = Request.QueryString;
//if any keys are in the url from the view
if (Request.QueryString.HasKeys())
{
//extract them out so that you can use them
//key = the name such as Part or Use it goes Key & Value this is passed to a Viewbag
//get(o) is getting the value at place 0, the first value in the url
ViewBag.querystringvalue0 = Request.QueryString.Get(0);
ViewBag.querystringvalue1 = Request.QueryString.Get(1);
}
//if there is any query string
if (Request.QueryString.HasKeys())
{
//pass the data to a couple of variables,
var parts = Request.QueryString.Get(0);
var use = Request.QueryString.Get(1);
//put them in a new query and return the results
ViewBag.getstock = from p in Bikeshopdb.Stocks
where p.PartName == parts && (p.Road == use || p.Mtn == use || p.Hybrid == use) select new
{
p.Item, p.Price, p.Quantity
};
}
return View(Bikeshopdb.Stocks.ToList());
答案 0 :(得分:0)
使用ViewModel类保存查询结果并传回视图。例如:
的HomeController
public class MatchingStock()
{
public int ID { get; set; }
public string Item { get; set; }
public int Price { get; set; }
public int Quantity { get; set; }
}
public ActionResult Index()
{
//...
var list =
(from p in Bikeshopdb.Stocks
where p.PartName == parts &&
(p.Road == use || p.Mtn == use || p.Hybrid == use)
select new MatchingStock() {
ID = p.ID,
Item = p.Item,
Price = p.Price,
Quantity = p.Quantity}).ToList();
ViewBag.getstock = list;
//...
}
查看
@foreach (var item in (List<MatchingStock>)ViewBag.getstock)
{
@item.Item @item.Price @item.Quantity
<br />
}