我有一个控制器方法,我想用它来发送视图列表和小数,而不使用模型。我怎么能这样做? 这是我对控制器视图的调用:
decimal totBalance = 10.0M;
return View(query.ToList(), totBalance);
答案 0 :(得分:4)
<强> 1.ViewBag 强>
将list
项Model
和ViewBage
中的总余额转换为。
public ActionResult ActionName()
{
var list= query.ToList();
decimal totBalance = 10.0M;
ViewBag.Banance= totBalance ;
return View(list);
}
使用:
@{
var list= Model;
var totBalance=ViewBag.Banance ;
}
<强> 2.ExpandoObject 强>
将动态对象传递为Model
。
public ExpandoObject ToExpando( object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
public ActionResult ActionName()
{
var list= query.ToList();
decimal totBalance = 10.0M;
var model= ToExpando(new{ ListValue=list,Balance =totBalance})
return View(model);
}
使用:
@{//don't need use @model List<ModelName> or something like as model
var list= Model.ListValue;
var totBalance=Model.Balance ;
}
答案 1 :(得分:0)
评论是正确的,这应该是一个模型。您最好的选择是创建一个模型,如:
public SomeModel
{
List<DatabaseEntity> Entity { get; set; }
decimal TotBalance { get;set; }
}
这将允许您在控制器中实例化它并使用query.ToList()和totBalance变量填充它。
然后您可以将其作为视图模型返回并轻松映射模型属性。
如果你不能(出于某种原因)使用模型类,@ MahediSabuj中提到的ViewBag方法是一个丑陋的解决方案,但是可行。您可以将一个或两个变量从控制器传递给ViewBag。
(控制器):ViewBag.TotBalance = totBalance;
(查看) - 只是一个例子:<p> @ViewBag.TotBalance </p>
一个问题是ViewBag将值存储为obj,如果需要进行任何计算等,则需要正确转换:
@if ( (decimal)ViewBag.TotBalance > 10.50) { ... }