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)
{

}





 

 

 

 

 

 

 

 

 

 

 

 



转载于:https://www.cnblogs.com/luoxiaonet/archive/2012/02/25/2368185.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值