It is simple MVC application to create online simple calculator using MVC and JQuery. This article provides a sample to create calculator using MVC 4 and JQuery.
Step 1: Create a new ASP.NET MVC 4 Application.
Step 2: Select Empty Project from Project Template.
Step 3: Select Razor view from view engine drop down list.->Click Ok.
Step 4: Add a home controller.
Step 5: Add this method which used to calculate.
- public string GetResult(string str)
- {
- List<char> symbleList = new List<char>();
- char[] charSymble = { '+', '-', '*', '/' };
- string[] st = str.Split(charSymble);
- for (int i = 0; i < str.Length; i++)
- {
- if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
- {
- symbleList.Add(str[i]);
- }
- }
- double result = Convert.ToDouble(st[0]);
- for (int i = 1; i < st.Length; i++)
- {
- double num = Convert.ToDouble(st[i]);
- int j = i - 1;
- switch (symbleList[j])
- {
- case '+':
- result = result + num;
- break;
- case '-':
- result = result - num;
- break;
- case '*':
- result = result * num;
- break;
- case '/':
- result = result / num;
- break;
- default:
- result=0.0;
- break;
- }
- }
- return result.ToString();
- }
Step 6: Add code for Index ActionResult method,
- public ActionResult Index()
- {
- if (Request["txt"] != null)
- {
- if (Request["txt"][Request["txt"].Length - 1] == '+' || Request["txt"][Request["txt"].Length - 1] == '-' || Request["txt"][Request["txt"].Length - 1] == '*' || Request["txt"][Request["txt"].Length - 1] == '/')
- {
- ViewBag.flag = 0;
- ViewBag.result = Request["txt"];
- }
- else
- {
- ViewBag.result = GetResult(Request["txt"]);
- ViewBag.flag = 1;
- }
- }
- return View();
- }
Step 7: Right click on Index method to add a view.
Step 8: Select Razor view from view engine.
Step 9: Uncheck create strongly-typed view check box.->Click Add.
Step 10: Add this code to design calculator on view,
Step 11: Run application.