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); } } }
@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.效果示范:
AspNet MVC4 教学-28:Asp.Net MVC4 Ajax技术实现除法取整取余快速Demo
原文:http://blog.csdn.net/vinglemar/article/details/46457523