How to calculate a parameter between multiple models? asp.net MVC
I have several models and I am trying to calculate a parameter called total. I am new to MVC and am not really sure how to do this or where (it can be seen that it shouldn't be done with that in mind).
I have this parameter that I have to calculate:
public class Bill
{
public int Total { get; set; }
}
using the following parameters:
public class Article
{
public int Price { get; set; }
public float Quantity { get; set; }
}
and:
public class BillLine
{
public int DiscountValue { get; set; }
}
The sum is calculated using these 3 values, but I'm not sure how. The program works as follows: each billLine can have 1 item and 1 bill can have many bill lines.
source to share
As per understanding, I have the following code: Given that it Quantity
refers to no of Items, it should be Int and Price Be a Float. TotalArticlePrice
is a computed property.
public class Article
{
public float Price { get; set; }
public int Quantity { get; set; }
public float TotalArticlePrice
{
get
{
return Price * Quantity;
}
}
}
As you mentioned one BillLine has one article, the model should be below: Article
and FinalBillLinePrice
, which is calculated by subtracting the discout value
public class BillLine
{
public int DiscountValue { get; set; }
public Article Article { get; set; }
public float FinalBillLinePrice
{
get
{
return Article.TotalArticlePrice - DiscountValue;
}
}
}
Finally, As you mentioned, One Bill
Can have several BillLine
, so the model should look like below where the property Total
stores the total ticket value.
public class Bill
{
public float Total
{
get
{
return BillLineList.Sum(x => x.FinalBillLinePrice);
}
}
public List<BillLine> BillLineList { get; set; }
}
In case I misunderstood anything, please let me know in the comments.
source to share
You will need to create a ViewModel by concatenating all three classes and it will be easy for you to do all the calculations with that.
To get started using the ViewModel see the links below.
source to share
Perhaps your view models should look something like this:
public class BillLine
{
public int DiscountValue { get; set; }
public Article Article {get; set; }
}
public class Bill
{
public List<BillLine> Lines { get; set;}
public int Total { get
{
int result;
foreach var line in Lines {
//Update result with your calculations
}
return result;
}
}
}
source to share