在上一节课程的MvcAddTest项目的基础上,继续完善演绎,增加了随机出题,及判断正误功能.
在原来的基础上,增加一个类文件,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcAddTest.Models { public class RandNum { private int firstNum; private int secondNum; public RandNum(bool bR) { if (bR != true) return; Random r1=new Random(); firstNum = r1.Next(100); Random r2 = new Random(); secondNum = r2.Next(50); } public int FirstNum { get { return firstNum; } set { firstNum = value; return; } } public int SecondNum { get { return secondNum; } set { secondNum = value; return; } } } }
修改原来的AddCal.cshtml文件:
@model MvcAddTest.Models.RandNum @{ ViewBag.Title = "AddCal"; } <h2>AddCal</h2> @using(Html.BeginForm("AddCal","Home")) { @Html.TextBox("FirstNum",@Model.FirstNum.ToString()) <text>+</text> @Html.TextBox("SecondNum",@Model.SecondNum.ToString())<text>=</text> @Html.TextBox("SumNum", (string)@ViewBag.strResult) @ViewBag.strOKErr <br /> <input type="submit" /> }
HomeCtroller.cs代码修改如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcAddTest.Models; namespace MvcAddTest.Controllers { public class HomeController : Controller { // GET: /Home/ public ActionResult Index() { return View(); } [HttpGet] public ActionResult AddCal() { RandNum rnObj = new RandNum(true); ViewData.Model = rnObj; @ViewBag.strResult = ""; ViewBag.strOKErr = ""; return View(); } [HttpPost] public ActionResult AddCal(string FirstNum, string SecondNum,string SumNum) { int a, b, c; a= int.Parse(FirstNum); b= int.Parse(SecondNum); c = int.Parse(SumNum); RandNum rnObj = new RandNum(false); rnObj.FirstNum=a; rnObj.SecondNum=b; if (c != (a + b)) ViewBag.strOKErr = "Err"; else ViewBag.strOKErr = "OK"; ViewBag.strResult = c.ToString(); ViewData.Model = rnObj; return View(); } } }
时间: 2024-11-05 19:25:21