gpt4 book ai didi

c# - 如何在 View ASP MVC 中使用模型数据?

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:14 24 4
gpt4 key购买 nike

我是 ASP MVC 的初学者,我正在尝试在 View 中显示来自模型的数据。这就是我显示数据的方式:

@Html.DisplayFor(modelItem => item.Budget_Year)

但我不知道如何使用这些数据,例如我试图将这个结果四舍五入,但我天真地尝试了:

@{ 
double test = (modelItem => item.Budget_Year);
test = System.Math.Round(test , 2);
}

但我不能那样使用它:无法将 lambda 表达式转换为类型“double”,因为它不是委托(delegate)类型

有人可以向我解释如何在我看来使用我模型中的这些不同项目吗?

最好的问候,

亚历克斯

最佳答案

你有很多方法可以更恰本地做到这一点:

使用 ViewModel 类,其中有一个属性是您的舍入值

public class MyViewModel {
public double BudgetYear {get;set;}
public double RoundedBudgetYear {get {return Math.Round(BudgetYear, 2);}}
}

在 View 中

@Html.DisplayFor(m => m.RoundedBudgetYear)

在您的属性上添加一个DisplayFormat 属性

参见 Html.DisplayFor decimal format?

创建您自己的 HtmlHelper,它会四舍五入显示的值。

@Html.DisplayRoundedFor(m => m.BudgetYear)

关于c# - 如何在 View ASP MVC 中使用模型数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com