MVC操作
1、在Models下写处理程序的类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace MvcDemo.Models 7 { 8 public class MyCalculator 9 { 10 /// <summary> 11 /// 计算平均成绩 12 /// </summary> 13 /// <param name="sumScore">总分</param> 14 /// <param name="sumSubject">科目总数</param> 15 /// <returns></returns> 16 public int GetAvg(int sumScore, int sumSubject) 17 { 18 return sumScore / sumSubject; 19 20 } 21 22 } 23 }
2、在Controllers下加入控制器
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 8 namespace MvcDemo.Controllers 9 { 10 public class CalculatorController : Controller 11 { 12 // 13 // GET: /Calculator/ 14 15 public ActionResult Index() 16 { 17 return View("MyCal");//如果用View(),返回与控制器动作方法同名视图,即Index.aspx,而View/Calculator下没有Index.aspx视图,肯定会出错 18 } 19 public ActionResult GetAvgScore() 20 { 21 //[1]接收提交的数据 22 int sumScore = Convert.ToInt32(Request.Params["sumScore"]); 23 int sumSubject = Convert.ToInt32(Request.Params["sumSubject"]); 24 //【2】调用模型处理数据 25 int result=new MvcDemo.Models.MyCalculator().GetAvg(sumScore,sumSubject); 26 //【3】返回视图(返回视图前,如果需要数据返回,必须先保存数据) 27 ViewData["avgScore"]="您的平均成绩是:" +result.ToString(); 28 return View("MyCal"); //能不能用View()呢?不行,View()返回的是与,即GetAvgScore视图,必须要显式的写上(无后缀名) 29 30 } 31 32 } 33 }
3、在Views加文件夹(与控制器同名),再加视图名称
1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> 2 3 <!DOCTYPE html> 4 5 <html> 6 <head runat="server"> 7 <meta name="viewport" content="width=device-width" /> 8 <title>MyCal</title> 9 </head> 10 <body> 11 <div> 12 13 <form method="post" action="/Calculator/GetAvgScore" > 14 <%--根据路由规则来填写action,即url: "{controller}/{action}/{id}",--%> 15 计算我的平均成绩:<br /> 16 科目总分:<input type="text" name="sumScore"/><br /> 17 科目总数:<input type="text" name="sumSubject"/><br /> 18 <input type="submit" value="开始计算"/> 19 20 </form> 21 <br /> 22 <%--ViewData能够在控制器和视图之间传递,通过键来获取值--%> 23 <%=ViewData["avgScore"] %> 24 </div> 25 </body> 26 </html>
MVC的程序入口:App_Start/RouteConfig下的Default路由来确定。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Web.Routing; 7 8 namespace MvcDemo 9 { 10 public class RouteConfig 11 { 12 public static void RegisterRoutes(RouteCollection routes) 13 { 14 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 16 routes.MapRoute( 17 name: "Default", 18 url: "{controller}/{action}/{id}", 19 //默认是Home/Index,程序入口 20 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 21 ); 22 } 23 } 24 }