ASP.NET MVC 3.0 知识记要(2)【RadioButtonList、CheckBoxList】

实践五.呈现RadioButtonList

  1.假如现在从数据库提取了一些数据:

List<Category> cateoryList = new List<Category>()
{
new Category(){
CategoryID = 1,
CategoryName = "公司内造"
},
new Category(){
CategoryID = 2,
CategoryName = "公司外购"
}
};

  

  2.通过Linq 将数据生成 SelectListItem 类型的集合,并赋予 ViewData["CategoryID"]

ViewData["CategoryID"] = (from item in cateoryList
select new SelectListItem()
{
Value = item.CategoryID.ToString(),
Text = item.CategoryName
}).ToList();

一定要调用 ToList(),否则会因为延迟查询而导致将 空ViewData["CategoryID"]被传入View层。

 

  3.在View层顶端,可以将 ViewData赋予本地变量

@{
List<SelectListItem> CategoryItems = ViewData["CategoryID"] as List<SelectListItem>;
}

  

  4.遍历集合生成 Radio出来:生成原生的HTML,

注意:radio的name 与 ViewData的键名相同。

for (int i = 0; i < @CategoryItems.Count; i++)
{
var isChecked = "";
SelectListItem item = @CategoryItems[i];
if (item.Selected == true)
{
isChecked = "checked = 'checked'";
}

<input type="radio" id="@string.Format("CategoryID_{0}", @i)" name="CategoryID" value="@item.Value" @isChecked />
<label for="@string.Format("CategoryID_{0}", @i)">@item.Text</label>
}


实践六. 呈现 CheckBoxList

  步骤分5步,前3步与上面一模一样,这里只说后面步骤:

  4.类型肯定是 checkbox;因为多选框本质是对一个集合的勾选,所以name可以适当以复数形式表现

for (int i = 0; i < @CategoryItems.Count; i++)
{
var isChecked = "";
SelectListItem item = @CategoryItems[i];
if (item.Selected == true)
{
isChecked = "checked = 'checked'";
}

<input type="checkbox" id="@string.Format("CategoryID_{0}", @i)" name="CategoryIDs" value="@item.Value" @isChecked />
<label for="@string.Format("CategoryID_{0}", @i)">@item.Text</label>
}

 

  5.基于Post请求的Action之参数,不妨添加一个 字符串数组,其名称与checkBox的name相同

[HttpPost]
public void EditOrder(Order order, string[] CategoryIDs)
{

}

对于包含着基础的string类型、int类型的属性,只要在基于Post请求的Action之参数中有同名出现,那么值就会被赋予其上,包括Order类里的属性也会被赋上值,尽管这看起来有些重复:

[HttpPost]
public void EditOrder(Order order, string[] CategoryIDs, string Description)
{

}





 

 

 

 

 

 

 

 

 

 

 

 



posted @ 2012-02-25 22:31  罗霄(Sto)  阅读(288)  评论(0编辑  收藏  举报