Reputation: 2959
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 :
@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
Someone can explain me how to use this different items from my model in my view ?
Best regards,
Alex
Upvotes: 2
Views: 41189
Reputation: 60493
you have many ways to do this more properly :
use a ViewModel class, where you have a property which is your Rounded value
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
see Html.DisplayFor decimal format?
or
Create your own HtmlHelper, which will round the displayed value.
@Html.DisplayRoundedFor(m => m.BudgetYear)
Upvotes: 7
Reputation: 4231
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. Keep the logic
in the controller / model and out of the view. This will make it easier to test as well
Upvotes: 0
Reputation: 26511
First you need to declare what model you will actually be using and then use it as Model
variable.
@model YourModelName
@{
var test = Model.BudgetYear.ToString("0.00");
}
Upvotes: 6
Reputation: 1620
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.
Upvotes: 0