AspNet MVC4 教学-2:AspNet MVC4 随机出题的简答加法 上次MVC课程的继续演绎

在上一节课程的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();
        }
    }
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。