MVC-- 网页中整、小数加法

首先看看总控制器:

 1 using FloatAddBox2.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 
 8 namespace FloatAddBox2.Controllers
 9 {
10     public class HomeController : Controller
11     {
12         //
13         // GET: /Home/
14 
15         public ActionResult Index()
16         {
17             return View();
18         }
19         [HttpGet]
20         public ActionResult FloatAdd()
21         {
22             return View();
23         }
24         [HttpPost]
25         public ActionResult CalSum(Box box)
26         {
27 
28             box.Sum = box.FirstNum + box.SecondNum;
29             return View("FloatAdd", box);
30         }
31     }
32 }

代码较短,其中的CalSum中把Box中的两数相加给了Sum,FloatAdd只是为View创建的空控制器,而Index中无任何代码,只是作为首页。

接下来看看View代码:

@model FloatAddBox2.Models.Box

@{
    ViewBag.Title = "FloatAdd";
}

<h2>FloatAdd</h2>

@using (Html.BeginForm("CalSum","Home",FormMethod.Post)) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Box</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstNum)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstNum)
            @Html.ValidationMessageFor(model => model.FirstNum)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.SecondNum)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.SecondNum)
            @Html.ValidationMessageFor(model => model.SecondNum)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Sum)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.Sum)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这个View中是对Model中的Box一个强类型。

而Index的View中只有显示标题的代码:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

 

Model中Box的代码:

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

namespace FloatAddBox2.Models
{
    public class Box
    {
        [Display(Name="加数")]
        [Range(0,100)]
        public float FirstNum { set; get; }

        [Display(Name = "加数")]
        [Range(0,100)]
        public float SecondNum { set; get; }
     [Display(Name = "和值")]
public float Sum { set; get; } } }

创建了三个:FirstNum,SecondNum,Sum 。

前两个的取值范围都为0~100之间,否则自动报错。。

三个都有着set和get。而且都作了汉化。

 

posted on 2018-08-19 11:14  格码拓普  阅读(305)  评论(0编辑  收藏  举报