MVC Calculator App: in This Workshop We Will Create A Web Calculator App

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

MVC Calculator App

In this workshop we will create a web calculator


app.
1. Open VS 2012 and create a new project. Make it asp.net MVC4
app and call it MvcCalculator:

2. Choose internet application as the project template.


3. Make sure you have the following in the solution:

4. You have a working app right now(we used a default template)!


Run the project. Note the IIS express(lightweight IIS) when you run
the app.
Adding a controller

5.Open the solution, right click on the controllers and add a controller,
name it “HelloWorldController”.

Note that the name of the controller must end with the controller key
word or else it won’t be recognized as a controller:

6.replace the content of the class with the following:


public string Index() {
return "This is my <b>default</b> action...";
}

public string Welcome() {


return "This is the Welcome action method...";
}

7. Run the app and navigate to the HelloWorld controller(don’t change


the port number which was randomly chosen by your system):
8. Navigate to the Welcome() method by:

Why in section 7 the index method was called automatically?

Because it’s the default behavior configured in the file: RouteConfig.cs


(located in the App_Start folder).

9. Change the default behavior such that the Welcome action is the
default method. Test it (you must restart the app):

Restore the default action to Index

This is the default url routing of MVC:

/[Controller]/[ActionName]/[Parameters]

10. Change the Welcome action and add parameters to it:


public string Welcome(string name, int numTimes = 1) {
return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " +
numTimes);
}

11. Navigate to the Helloworld Welcome action and supply the


parameters:

The presentation layer: Adding a view


12. A view is file with a .cshtml extension. This file is an HTML file edited
with the razor engine of MVC.

Open the HelloWorld controller and change the index action :


public ActionResult Index() {
return View();
}

13. Adding the view : Right click inside the index method and select add
view:

Leave the defaults AS IS and click Add button.


A new file in the Views folder was added. It’s name : Index.cshtml

14. Add the following to the view:

<p> ‫< ?עד מתי קורס דיזיין פטרנז‬/p>

Run the app and navigate to the page:

14. changing the layout:

The layout is the HTML container file .By default all the views that we
create are appended to it. Open the file _Layout.cshtm:

Change the “<p class="site-title">@Html.ActionLink("your logo here",


"Index", "Home")</p>”

To:
<p class="site-title">@Html.ActionLink("Web Calculator", "Index",
"Home")</p>
Replace the title with:

<title>@ViewBag.Title – Calculator app</title>

(the title influence the title in the tab of the browser)

Test the app by running it.

Passing data from controller to view:

Controller classes are invoked in response to an incoming URL


request. A controller class is where you write the code that handles
the incoming browser requests, retrieves data from a database, and
ultimately decides what type of response to send back to the
browser. View templates can then be used from a controller to
generate and format an HTML response to the browser.

Controllers are responsible for providing whatever data or objects are


required in order for a view template to render a response to the
browser.

Currently, the Welcome action method in the HelloWorldController


class takes a name and a numTimes parameter and then outputs the
values directly to the browser. Rather than have the controller render
this response as a string, let’s change the controller to use a view
template instead. The view template will generate a dynamic
response, which means that you need to pass appropriate bits of
data from the controller to the view in order to generate the
response. You can do this by having the controller put the dynamic
data (parameters) that the view template needs in a ViewBag object
that the view template can then access.

15. Return to the HelloWorldController.cs file and change the


Welcome method to add a Message and NumTimes value to the
ViewBag object. ViewBag is a dynamic object, which means you can
put whatever you want in to it.

public ActionResult Welcome(string name, int numTimes = 1)


{
ViewBag.Message = "Hello " + name;
ViewBag.NumTimes = numTimes;
return View();
}
Compile the project.(Build->Build solution)
16. Adding the Welcome view : right click inside the welcome method
and select Add view. Leave the defaults AS IS and click ADD:

17. copy paste the following to the Wecome.cshtml view:

@{
ViewBag.Title = "Welcome";
}
<h2>Welcome</h2>
<ul>
@for (int i=0; i < ViewBag.NumTimes; i++) {
<li>@ViewBag.Message</li>
}
</ul>
Run the application and browse to the following URL:

http://localhost:xx/HelloWorld/Welcome?name=yourname&numtimes=10

Now data is taken from the URL and passed to the controller using the
model binder. The controller packages the data into a ViewBag object and
passes that object to the view. The view then displays the data as HTML to
the user.
The BL layer: Adding a model
We’ll create a class that perform the 4 basic arithmetic
operations:
Increment, Subtract, Multiply and Divide.
18. click on the model folder and Add a new class. Call it
calculator:

19. implement the 4 arithmetic operations:


Ex:
public int Increment(int x, int y) {
return x + y;
}
20. Create a new controller and name it Calculator:

21. Create a new View by right clicking inside the index


method and selecting “Add View”.Leave the defaults AS
IS:
22. Copy paste the following to the new view we’ve just
created:
@{
ViewBag.Title = "Calculator";
}

<h2>My Web Calculator</h2>

<form id="frm" method="post">


<p>param1 : <input type="text" name="param1" style="width:50px"
value="@ViewBag.x"/></p>
<p>param2 : <input type="text" name="param2" style="width:50px"
value="@ViewBag.y"/></p>
<p>Result : <input type="text" name="result" style="width:150px"
value="@ViewBag.result" /></p>
<p>
<button type="submit"
formaction="/Calculator/Increment">Increment</button>
</p>
</form>

22. Copy paste the following to the new view we’ve just
created:

23. Add an increment Method to the calculator controller:


public ActionResult Increment(FormCollection frm) {

int x, y, result;

Calculator calc = new Calculator();


int.TryParse(frm["param1"].ToString(), out x);
int.TryParse(frm["param2"].ToString(), out y);
result = calc.Increment(x, y);

ViewBag.x = x;
ViewBag.y=y;
ViewBag.result = result;
return View("Index");
}

23. Test the app by navigating to the controller.


24 Change the default controller from “Home” to
“Calculator” in the RouteConfig.cs file.

25. Add the rest of the buttons to the index view:


subtract, multiply and divide.
26. Implement those operation in our controller

You might also like