简体   繁体   中英

How to calculate a parameter between multiple models? asp.net MVC

I have multiple models and I am trying to calculate a parameter named total. I am new to MVC and are not really sure how to do this or where (seen that it should not be done in view that's for sure).

I have this parameter I have to calculate:

public class Bill
{
public int Total { get; set; }
}

by using these parameters:

public class Article
{
   public int Price { get; set; }
   public float Quantity { get; set; }
}

and also:

public class BillLine
{
   public int DiscountValue { get; set; }
}

The total is calculated using those 3 values but I am not really sure how to do it. The program works like this: each billLine can have 1 article and 1 bill can have many bill lines.

As per understanding I have following Code: Considering Quantity refers to no of Items it should be Int and Price Be a Float property. TotalArticlePrice is a calculated property.

public class Article
{
    public float Price { get; set; }
    public int Quantity { get; set; }


    public float TotalArticlePrice
    {
        get
        {
            return Price * Quantity;
        }

    }
}

As you mentioned that one BillLine has one Article so model should be as below with Article property and FinalBillLinePrice which is calculated deducting 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 May have Multiple BillLine ,therefore Model should look like below, where Total property stores the Total Bill Price.

public class Bill
{
    public float Total
    {
        get
        {

            return BillLineList.Sum(x => x.FinalBillLinePrice);

        }

    }
    public List<BillLine> BillLineList { get; set; }
}

In case, I have misunderstood anything Please brief in comments.

You will need to create a ViewModel by combining all the three classes and it will be easy for you to do all the calculation using this.

To get started in Using ViewModel, please refer the links below.

Understanding ViewModel in ASP.NET MVC

Multiple Models in a View in ASP.NET MVC 4 / MVC 5

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

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