[2019编程]第三节教学大纲:利用Model完成一个基本除法模型,并完成一个简单的除法应用

it2022-05-05  162

目录

 

第一步:创建项目

第二步:创建控制器

第二步:创建类文件

第四步:创建视图

第五步:运行

小结及补充


第一步:创建项目

新建一个C#,Asp.net MVC4,基本 项目,名称:MvcDivTest

第二步:创建控制器

在Controllers目录下,新建一个Home控制器,代码文件 HomeController.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcDivTest.Models; namespace MvcDivTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult CalAnswer(DivModel box) { if (box.Divisor == 0) { ModelState.AddModelError("", "除数不能为0."); ModelState.AddModelError("Divisor", "除数不能为0."); return View("Index", box); } box.Answer = box.Dividend / box.Divisor; box.Remainder= box.Dividend % box.Divisor; return View("Index",box); } } }

完成后,编译.

第二步:创建类文件

在Models目录下,新建一个类文件: DivModel.cs

 

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace MvcDivTest.Models { public class DivModel { [Display(Name = "被除数")] public int Dividend { set; get; } [Display(Name = "除数")] public int Divisor { set; get; } [Display(Name = "商")] public int Answer { set; get; } [Display(Name = "余数")] public int Remainder { set; get; } } }

第四步:创建视图

在上述的Index Action中的大括号中,右击 添加一个Index视图,Index.cshtml:

弹出选项对话框,设置按照红色框标注,如下图:

最后产生一个Index.cshtml文件:

按照红色框标注,对此文件修改后如下:

最终的Index.cshtml如下:

@model MvcDivTest.Models.DivModel @{ ViewBag.Title = "Index"; } <h2>Index</h2> @using (Html.BeginForm("CalAnswer","Home")) { @Html.ValidationSummary(true) <fieldset> <legend>除法测试</legend> <div class="editor-label"> @Html.LabelFor(model => model.Dividend) </div> <div class="editor-field"> @Html.EditorFor(model => model.Dividend) @Html.ValidationMessageFor(model => model.Dividend) </div> <div class="editor-label"> @Html.LabelFor(model => model.Divisor) </div> <div class="editor-field"> @Html.EditorFor(model => model.Divisor) @Html.ValidationMessageFor(model => model.Divisor) </div> <div class="editor-label"> @Html.LabelFor(model => model.Answer) </div> <div class="editor-field"> @Html.DisplayFor(model => model.Answer) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remainder) </div> <div class="editor-field"> @Html.DisplayFor(model => model.Remainder) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

第五步:运行

最后测试效果:

效果A:

效果B:

效果C:

小结及补充

1.Models下方的类文件,可以做盒子,盒子的可以接收传递数据,此类可以产生强视图,此类可以汉化界面,此类可以辅助验证.

2.强类型视图,可以人工定制修改.

3.少量的,零散的数据传递考虑使用ViewBag之类对象,大量的,规范的数据传递考虑使用强视图配合类盒子.

源码下载


最新回复(0)