[英]How to use Model data in a view ASP MVC?
I'm a beginner with ASP MVC and I'm trying to show data from a model in a view. 我是ASP MVC的初学者,我试图在视图中显示模型中的数据。 This is how I display the data :
这就是我显示数据的方式:
@Html.DisplayFor(modelItem => item.Budget_Year)
But I don't know how to use this data, for example I tried to round up this result and I tried naively : 但是我不知道如何使用这些数据,例如,我试图对结果进行取整,但是我很天真地尝试了:
@{
double test = (modelItem => item.Budget_Year);
test = System.Math.Round(test , 2);
}
But I can't use it like that : Cannot convert lambda expression to type 'double' because it is not a delegate type 但我不能这样使用: 无法将lambda表达式转换为类型'double',因为它不是委托类型
Someone can explain me how to use this different items from my model in my view ? 有人可以解释我如何从模型中使用这些不同的项目?
Best regards, 最好的祝福,
Alex 亚历克斯
you have many ways to do this more properly : 您有很多方法可以更正确地做到这一点:
use a ViewModel class , where you have a property which is your Rounded value 使用ViewModel类 ,其中有一个属性,即Rounded值
public class MyViewModel {
public double BudgetYear {get;set;}
public double RoundedBudgetYear {get {return Math.Round(BudgetYear, 2);}}
}
and in View 并在视野中
@Html.DisplayFor(m => m.RoundedBudgetYear)
or 要么
Add a DisplayFormat attribute on your property 在属性上添加DisplayFormat属性
see Html.DisplayFor decimal format? 看到Html.DisplayFor十进制格式?
or 要么
Create your own HtmlHelper , which will round the displayed value. 创建您自己的HtmlHelper ,它将舍入显示的值。
@Html.DisplayRoundedFor(m => m.BudgetYear)
First you need to declare what model you will actually be using and then use it as Model
variable. 首先,您需要声明您将实际使用的模型,然后将其用作
Model
变量。
@model YourModelName
@{
var test = Model.BudgetYear.ToString("0.00");
}
If you're just trying to access a property of the model you can do it like this: 如果您只是尝试访问模型的属性,则可以这样做:
double test = Model.BudgetYear;
The lambda is only necessary if you're trying to have the user assign a value to it from the view. 仅当您试图让用户从视图为其分配值时,才需要lambda。
I wouldn't do this in the view. 我不会在视图中这样做。 Instead I would round
BudgetYear
in your model / view model and send it down to the View already rounded. 相反,我会在您的模型/视图模型中对
BudgetYear
,然后将其发送到已经四舍五入的View。 Keep the logic
in the controller / model and out of the view. 将
logic
保留在控制器/模型中,并置于视图之外。 This will make it easier to test as well 这也将使测试更加容易
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.