Tuesday, September 22, 2015


Add 2 numbers in MVC
Download the sample project from the link below:

- Create a new project in Visual Studio.

- Name the project as "MVCDemoCalc".

- Click Ok.
- In the next screen, select "Internet Application" in Project Template and Razor as View Engine. Click Ok.

- A new project opens. You will see 3 folders in the Solution Explorer named as View, Controller and Model as shown below.

- Create a New class named as MathCalc in the Model folder. Define a method named as Sum to add the 2 numbers.
public class MathCal
        public double Value1 { get; set; }
        public double Value2 { get; set; }
        public double Sum(double v1, double v2)
            return v1+v2;


- Create a controller "MathCalController" in Controller folder.

- This class uses the MathCal class object. Below is the code:
  public class MathCalController : Controller
        // GET: /MathCal/         
        public ActionResult Index(MathCal objMathCal)
            ViewBag.Results = objMathCal.Sum(objMathCal.Value1, objMathCal.Value2);
            return View(objMathCal);


- Compile the project to generate classes.
- Right click the ActionResult to generate the detail view.

- Give View Name as 'Index'. View Enginer as Razor. Select the checkbox 'Create a strongly typed view'. Selec the model class 'MathCal'. Choose Scaffold Template as Details. Click select. Below is the modified code of Index.cshtml:

@model MVCDemoCalc.Models.MathCal

    Layout = null;

<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    using (@Html.BeginForm())

        <div class="display-label">
            @Html.DisplayNameFor(model => model.Value1)
            @Html.EditorFor(model => model.Value1)

        <div class="display-label">
            @Html.DisplayNameFor(model => model.Value2)
            @Html.EditorFor(model => model.Value2)

        <div class="display-label">
        <input type="submit" value="Add" />


- Open RoutConfig.cs file located in App_Start folder. Change the default startup page as below:
public static void RegisterRoutes(RouteCollection routes)

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "MathCal", action = "Index", id = UrlParameter.Optional }


- Run the program and check the output. Here below is the ouput: