Mvc4中的WebGrid控件问题

时间:2013-09-16 16:16:18

标签: jquery asp.net-mvc-4 razor checkbox webgrid

我是MVC的新手,我正在尝试在我的演示应用程序中使用WebGird控件我做了如下的任务: -

的HomeController

public ActionResult Index()
        {
            List<Student> listStudent = new List<Student>();
            listStudent.Add(new Student { Id = 1000, Name = "Sumit Kesarwani", IsActive = true });
            listStudent.Add(new Student { Id = 1001, Name = "Arun Singh", IsActive = true });
            listStudent.Add(new Student { Id = 1002, Name = "Vijay Shukla", IsActive = false });
            listStudent.Add(new Student { Id = 1003, Name = "Pwan Shukla", IsActive = true });
            var data = listStudent;

            return View(data);
        }

Student.cs

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
    }

Index.cshtml

@model IEnumerable<MvcWebGrid.Models.Student>

@{
    ViewBag.Title = "Home Page";
    WebGrid webGrid = new WebGrid(Model);
}
@webGrid.GetHtml(columns: new[]{
  webGrid.Column("Id"),
  webGrid.Column("Name"),
  webGrid.Column("IsActive", header: "", format:@<text><input name="isActive" 
      type="checkbox" @item.IsActive == "true" ? "checked" : ""/></text>)
})

以上WebGrid将以readonly模式显示所有数据,但我需要这些数据将以可编辑模式显示,例如ID将显示在隐藏字段中,名称将显示在Textbox和当数据加载checkbox检查其属性是否为真值时,将检查checkbox,如果属性为false,则checkboxuncheck

请请帮助我!

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

以下代码是我对您的问题的看法

@model IEnumerable<MvcWebGrid.Models.Student>

@{
    ViewBag.Title = "Home Page";
    var webGrid = new WebGrid(Model);
    Func<bool, MvcHtmlString> func = 
    (b) => b ? MvcHtmlString.Create("checked=\"checked\"") : MvcHtmlString.Empty;
}

@webGrid.GetHtml(columns: new[]{
  webGrid.Column("Id" ,header: "", format:
  @<text>
      <input name="id" type="hidden" value="@item.Id" />
  </text>),
  webGrid.Column("Name", header: "", format:
  @<text>
      <input name="name" type="text" value="@item.Name"/>
  </text>),
   webGrid.Column("IsActive", header: "", format:
   @<text>
       <input name="isActive" type="checkbox" @func(item.IsActive)/>
   </text>)
 })