代码参考:
1.创建控制器:
using MvcTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Check1()
{
return View();
}
public ActionResult Accept1(bool? BeLate)
{
ViewBag.Check1 = BeLate;
return View("Check1");
}
public ActionResult Check2()
{
ViewBag.Check2 = false;
return View();
}
public ActionResult Accept2(bool BeLate)
{
ViewBag.Check2 = BeLate;
return View("Check2");
}
public ActionResult Check3()
{
CheckBox box = new CheckBox();
return View(box);
}
public ActionResult Accept3(CheckBox box)
{
return View("Check3",box);
}
}
}
2.创建View:
Index.cshtml:
@{
ViewBag.Title = "Index";
}
<h2>Check Button的三种测试</h2>
<ul>
<li>@Html.ActionLink("传统方法","Check1")</li>
<li>@Html.ActionLink("助记符A:弱类型","Check2")</li>
<li>@Html.ActionLink("助记符B:强类型","Check3")</li>
</ul>
Check1.cshtml:
@{
ViewBag.Title = "Check1";
}
<h2>Check1: @if (ViewBag.Check1 != null)
{
@ViewBag.Check1
}
else
{
<span>值为空</span>
}
</h2>
@using (Html.BeginForm("Accept1", "Home"))
{
<input type="checkbox" name="BeLate" value="true" />
<input type="submit" value="提交 " />
}
Check2.cshtml:
@{
ViewBag.Title = "Check2";
}
<h2>Check2: @if (ViewBag.Check2!= null)
{
@ViewBag.Check2
}
else
{
<span>值为空</span>
}
</h2>
@using (Html.BeginForm("Accept2", "Home"))
{
@Html.CheckBox("BeLate",(bool)@ViewBag.Check2)
<input type="submit" value="提交 " />
}
Check3.cshtml:
@model MvcTest.Models.CheckBox
@{
ViewBag.Title = "Check3";
}
<h2>Check3:@Model.BeLate</h2>
@using (Html.BeginForm("Accept3","Home",FormMethod.Post)) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CheckBox</legend>
<div class="editor-label">
@Html.LabelFor(model => model.BeLate)
</div>
<div class="editor-field">
@* @Html.EditorFor(model => model.BeLate)*@
@Html.CheckBoxFor(model=>model.BeLate)
@Html.ValidationMessageFor(model => model.BeLate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}