How to make simple calculations using model items and an input from a form in ASP.net MVC 3?

Seeing as you say you're new to MVC, I've given you a few options and explained which is best and why, because it's better to understand now so you don't get in to bad habits, especially if you start building larger projects.

You don't necessarily need to create a variable, because you can do that calculation in your view. Because you are passing the domain model directly to the view you can do (in razor):

@(Model.Quantity * Model.Rates.Amount)

Although this is the easiest option I wouldn't necessarily recommend this as views should be dumb - see ASP.NET MVC: How dumb should my view be?.

Another option is to do the calculation in the controller and pass the value in the ViewBag, e.g.:

public ViewResult Details(int id)
{
    ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
    ViewBag.Price = projectmaterial.Quantity * projectmaterial.Rates.Amountl
    return View(projectmaterial);
}

Then you could use it in your view like:

@ViewBag.Price

Again, this is easy but I wouldn't recommend it, as ViewBag isn't strongly typed - see Is using ViewBag in MVC bad?.

You could put a property on your ProjectMaterial class like, which is a neat solution.

public decimal Price
{
    get
    {
        return Quantity * Rates.Amount;
    }
}

However, if Price is a property that is only ever used within your views (ie you just display it) then it probably shouldn't be in your domain model, as your domain model is just that - storing and accessing the raw data.

Maybe the best way is to create a viewmodel specific to your view (see http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx) with a Price propert. This means that the property is only used where it is needed, the domain model remains just that, your view remains dumb and your domain model is not exposed to your view. See Why Two Classes, View Model and Domain Model? also for a good explanation of view models


You could add a property to your ProjectMaterial model:

public decimal Price
{
    get
    {
        return Quantity * Rates.Amount;
    }
}