C# 如何在视图 ASP MVC 中使用模型数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16688099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:39:52  来源:igfitidea点击:

How to use Model data in a view ASP MVC?

c#asp.netasp.net-mvcviewmodel

提问by Alex

I'm a beginner with ASP MVC and I'm trying to show data from a model in a view. This is how I display the data :

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

@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

亚历克斯

采纳答案by Rapha?l Althaus

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 attributeon 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)

回答by Colm Prunty

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。

回答by Simon Martin

I wouldn't do this in the view. Instead I would round BudgetYearin your model / view model and send it down to the View already rounded. Keep the logicin the controller / model and out of the view. This will make it easier to test as well

我不会在视图中这样做。相反,我会BudgetYear在您的模型/视图模型中舍入并将其发送到已经舍入的视图。保持logic在控制器/模型和视图之外。这也将使测试更容易

回答by Stan

First you need to declare what model you will actually be using and then use it as Modelvariable.

首先,您需要声明实际使用的模型,然后将其用作Model变量。

@model YourModelName
@{
    var test = Model.BudgetYear.ToString("0.00");
}