C# 关于MVC框架的简单实例(计算器)

一、需求分析

实现效果

 

二、实现步骤

 

步骤一:新建项目--->Web---->空模板

 

步骤二:添加控制器

步骤三:根据控制器名称添加视图

步骤四:添加Models模型  编写具体的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCDemo.Models
{
    public class Calculator
    {
        public int getAVG(int sumScore,int sumSubject)
        {
            return sumScore / sumSubject;
        }
    }
}

步骤五:编写视图,具体展示的内容


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CalculatorView</title>
</head>
<body>
    <form method="post" action="/Calculator/Calculate">
        计算平均成绩<br/>
        总成绩:<input type="text" name="sumScore" /> <br/>
        总科目:<input type="text" name="sumSubject" /><br/>
        <input type="submit"  value="开始计算"/><br/>
        @ViewData["avgScore"]  
    </form>
   
</body>
</html>

步骤六:编写控制器活动方法

using MVCDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDemo.Controllers
{
    public class CalculatorController : Controller
    {
        // GET: Calculator
        public ActionResult Index()
        {
            return View("CalculatorView");
        }

        public ActionResult Calculate()
        {
            //[1]获取数据
            int sumScore = Convert.ToInt32(Request.Params["sumScore"]);
            int sumSubject = Convert.ToInt32(Request.Params["sumSubject"]);
            //[2]处理数据
            Calculator objCal = new Calculator();
            int avgScore = objCal.getAVG(sumScore, sumSubject);
            //[3]返回数据
            ViewData["avgScore"] = "平均成绩为:" + avgScore;
            return View("CalculatorView");
        }
    }
}

步骤七:修改路由

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Calculator", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 

posted @ 2018-04-26 11:34  CG_Technology  阅读(1942)  评论(0编辑  收藏  举报