2

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

Alex
  • 2,927
  • 8
  • 37
  • 56

4 Answers4

7

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)
Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
4

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");
}
Stan
  • 25,744
  • 53
  • 164
  • 242
  • Ok, I get it, I'm in a loop @foreach (var item in Model) so I need to use item.Budget_Year. Thank for the help. – Alex May 22 '13 at 09:33
0

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.

Colm Prunty
  • 1,595
  • 1
  • 11
  • 29
0

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

Simon Martin
  • 4,203
  • 7
  • 56
  • 93