从另一个类访问该值以在控制器中进行计算

时间:2014-08-25 02:22:47

标签: c# asp.net-mvc asp.net-mvc-5

我正在使用C#和MVC5进行Web应用程序。如何使用其他类中的值在控制器中进行计算?例如,我有两个类:Product和Calculation。产品类看起来像这样:

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public decimal ProductPrice { get; set; }

public virtual ICollection<Calculation> Calculations { get; set; }       
}

计算类如下所示:

public class Calculation
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public decimal Quantity { get; set; }
    public decimal TotalPrice { get; set; }

    public virtual Product Product { get; set; }

}

因此,当从组合框中选择产品时,我希望该方法使用所选产品的价格(这是产品类的属性)和数量(这是类计算的属性)来计算TotalPrice。因此,在我的CalculationController中,方法Create看起来像这样:

// GET: Calculation/Create
    public ActionResult Create(int? id)
    {
        ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName");
        return View();
    }

// POST: Calculation/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "Id,ProductId,Quantity,TotalPrice")] Calculation calculation)
    {


        if (calculation.TotalPrice == null)

        {

// So this part doesn’t work because it can’t access the value of ProductPrice property from another class.
            calculation.TotalPrice = product.ProductPrice * Quantitiy;

            db.Calculations.Add(calculation);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }


        ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName", calculation.ProductId);
        return View(calculation);
    }

我意识到我需要初始化它才能使用来自另一个类的值,但是有人可以尝试在这个例子中解释如何做到这一点,因为我经常做错事。

谢谢。

1 个答案:

答案 0 :(得分:0)

通过查看代码,您可以使用Entity Framework,并将Product属性延迟加载到Calculation类中(通过使用virtual关键字)。这将使您第一次访问它时可用。

但您的问题是您应该将其作为该计算的属性进行访问,即

calculation.TotalPrice = calculation.Product.ProductPrice * Quantitiy;

您可能会看到应该避免访问该产品价格的空异常,因此您应该确保(和/或进行空检查)计算的Product属性已正确初始化。

为了初始化它,你应该在访问它之前做到:

calculation.ProductId = productId //The one you're getting in the post

由于这个ProductId属性是let&#39; s&#34;外键&#34;了解EF如何使用这些导航属性。