AspNet MVC4 教学-6:AspNet MVC4 CheckBox控件测试演示

类文件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>
}
}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。