类文件Box.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcCheckBoxTest.Models { public class Box { [Display(Name = "爱好")] public IEnumerable<SelectListItem> Hobbies { get; set; } } }
HomeController.cs文件:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcCheckBoxTest.Models; namespace MvcCheckBoxTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { Box model = new Box(); var roles = new[] { new SelectListItem { Value = "read", Text="看书", Selected = false }, new SelectListItem { Value = "game", Text="游戏",Selected = true }, new SelectListItem { Value = "inter", Text="上网",Selected = false } }; model.Hobbies = roles; return View(model); } public ActionResult Submit(string[] Hobbies) { ViewBag.Hobbies = Hobbies; return View(); } } }
Index.cshtml:
@model MvcCheckBoxTest.Models.Box @{ ViewBag.Title = "Index"; } <h2>Index</h2> @using (Html.BeginForm("Submit","Home")) { foreach (SelectListItem item in Model.Hobbies) { var ischecked = ""; if (item.Selected) { ischecked = "checked='checked'"; } <input name="Hobbies" type="checkbox" value="@item.Value" @ischecked /> @item.Text } <input type="submit" value="提交" /> }
Submit.cshtml:
@{ ViewBag.Title = "Submit"; } <h2>Submit</h2> @{ if(ViewBag.Hobbies!=null) { for(int i=0;i<ViewBag.Hobbies.Length;i++) { <h2>@ViewBag.Hobbies[i]</h2> } } }
时间: 2024-10-21 10:03:28