DotnetSparrow
DotnetSparrow

Reputation: 27996

integer output instead of string

I have created some static functions that return integer. In my view I want sum of these functions. I am using following code:

@myrepository.OverDraftCount() +
@myrepository.MortgageCount() +
@myrepository.InstallmentCount()+
@myrepository.RevolvingCount()+
@myrepository.OthersCount()

But it is returning 2 + 2+ 2 + 2 + 2 instead of 10 which it considers all these function's output as string. How can I change it ?

Thanks

Upvotes: 0

Views: 126

Answers (2)

Sergi Papaseit
Sergi Papaseit

Reputation: 16174

The Razor view engine will treat everything as a string (HTML rendering means outputting a bunch of strings), so you'll need to perform the sum in a code block and the display it.

Try:

@{ 
    var sum = myrepository.OverDraftCount() +
        myrepository.MortgageCount() +
        myrepository.InstallmentCount()+
        myrepository.RevolvingCount()+
        myrepository.OthersCount();
}

Then you can use the sum variable in your html:

<span>@sum</span>

EDIT to clarify all the upheaval:

As I have extensively stated in the comments, This will solve your problem, but it is hardly the neatest way to accomplish what you want. As I see it, you have 2 better options:

  1. Either take the approach in @Darin Dimitrov's answer or
  2. Perform the calculation in the controller and pass the sum value to the view, either as part of a View Model or through the ViewBag.

Upvotes: -1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You just forgot to add a Sum method to this class:

public decimal Sum()
{
    return OverDraftCount() + 
           MortgageCount() + 
           InstallmentCount() + 
           RevolvingCount() + 
           OthersCount();
}

so that in your view:

@myrepository.Sum()

Views should be as dumb as possible. They are so dumb that are not even capable of adding numbers. Do not code such logic into them. They should only show information that is passed to them, not try to calculate and fetch data. That's not their responsibility.

Upvotes: 6

Related Questions