AspNet MVC4 教育-28:Asp.Net MVC4 Ajax技术部门四舍五入余速Demo
A.创建一个Basic项目类型。
B.于Models创建一个文件夹:
DivModel.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace MvcAjaxDivTest.Models { public class DivModel { [Required(ErrorMessage = "请输入一个整数.")] public int Dividend {set; get;} [Required(ErrorMessage = "请输入一个整数.")] public int Divisor {set; get;} public int? Answer { set; get; } public int? Remainder { set; get;} } }
C.创建HomeController.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcAjaxDivTest.Models; namespace MvcAjaxDivTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult Div(DivModel m) { if (m.Divisor == 0) { return Json(new { DivisorTip = "除数不能为0", Answer = "", Remainder = "" }, JsonRequestBehavior.AllowGet); } return Json(new { DivisorTip= "", Answer = m.Dividend / m.Divisor, Remainder = m.Dividend % m.Divisor }, JsonRequestBehavior.AllowGet); } } }
D.创建对应的Home/Index.cshtml:
@model MvcAjaxDivTest.Models.DivModel @{ ViewBag.Title = "Ajax Div Test"; } <h2>Ajax Div Test</h2> @using (Ajax.BeginForm("Div", "Home", new AjaxOptions {OnSuccess = "ShowResult"})) { @Html.ValidationSummary(true) <fieldset> <legend>DivModel</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)<span id="DivisorTip"></span> @Html.ValidationMessageFor(model => model.Divisor) </div> <div class="editor-label"> @Html.LabelFor(model => model.Answer) </div> <div id="Answer" class="editor-field"> @Html.DisplayFor(model => model.Answer) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remainder) </div> <div id="Remainder" class="editor-field"> @Html.DisplayFor(model => model.Remainder) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } @*<script src="/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>*@ @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script language="javascript" type="text/javascript"> function ShowResult(data) { $("#DivisorTip").html(data.DivisorTip); $("#Answer").html(data.Answer); $("#Remainder").html(data.Remainder); } </script> }E.效果示范:
版权声明:本文博主原创文章,博客,未经同意不得转载。