简体   繁体   中英

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. 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

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)

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");
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM