MVC小练习——计算器(求平均数)

First step:create a new MVC project

MVC小练习——计算器(求平均数)

change the solution name and project name.
then choose project template:

MVC小练习——计算器(求平均数)
MVC小练习——计算器(求平均数)

Second step:add a controller and a view and a class.


MVC小练习——计算器(求平均数)

Third step: edit the Index1.aspx in Views;

<div>
        <form method="post" action="/Calculator/GetAverage">
            请输入总分数:<input type="text" name="sumScore"/>
            请输入总科目:<input type="text" name="sumObject">
            <input type="submit" value="计算">
        </form>
    </div>

fourth step: edit the models named GetAverage;

public class GetAverage
    {
        public int GetAvg(int sumScore, int sumObject) 
        {
            return sumObject == 0 ? 0 : sumScore / sumObject; 
        }
    }

fifth step: edit the controler ;

 public ActionResult GetAverage()
        {
            //接收数据
            int sumScore = Convert.ToInt32(Request.Params["sumScore"]);
            int sumObject = Convert.ToInt32(Request.Params["sumObject"]);
            //调用models里的方法
            GetAverage getAvg = new GetAverage();
            int result = getAvg.GetAvg(sumScore,sumObject);
            //保存需要传递的数据
            ViewData["avgScore"] = "平均成绩为:" + result;
            return View("Index1");

        }

last step: in Views, get data from controler;

<%=ViewData["avgScore"] %>

ok, game over.

MVC小练习——计算器(求平均数)