mvc中使用Dictionary呈现checkbox遇到的问题
我有一个Dictionary 类型
public static class ghDictionary
{
public static Dictionary<int,string> getOpendict()
{
Dictionary<int, string> open_dict = new Dictionary<int, string>();
open_dict.Add(1, "奖金使用、分配考核情况");
open_dict.Add(2, "职工两违情况");
open_dict.Add(3, "等级考评情况");
open_dict.Add(4, "困补费救济情况");
open_dict.Add(5, "各项评先情况");
open_dict.Add(6, "竞争上岗实施方案实施过程及结果情况");
open_dict.Add(7, "民主评议车间干部、班子集体工作情况");
open_dict.Add(8, "车间认为应向职工公开的事项和涉及职工切身利益的其他事项情况");
open_dict.Add(9, "其他");
return open_dict;
}
}
两个 添加的动作
#region 添加
public ActionResult Create()
{
ViewBag.OpenItemDictiony = ghDictionary.getOpendict(); //这里呈现Dictionary
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create([Bind(Include = "ID,UID,OpenItem,OpenContent,OpenFormally,OpenDate,PName,InputDateTime")] tz_OpenTransaction ot) //上面的Dictionary里的的value值 对应这里的OpenItem参数
{
if (ModelState.IsValid)
{
if (db.tz_OpenTransactions.FirstOrDefault(o => o.UID == ot.UID && o.OpenDate == ot.OpenDate) != null)
{
ModelState.AddModelError("OpenDate", "您已经有相同日期的事务公开记录,请选择其他日期!");
return View(ot);
}
try
{
ot.InputDateTime = DateTime.Parse(DateTime.Now.ToString());
db.tz_OpenTransactions.Add(ot);
db.SaveChanges();
TempData["Message"] = "添加成功!";
return RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddModelError("OpenContent", "新增失败,请稍后重试!" + ex.Message);
return View(ot);
}
}
return View(ot);
}
#endregion
视图如下:
......前面的html略
<div class="col-sm-12">
<span>公开项目:</span>
@foreach (var item in (Dictionary<int, string>)ViewBag.OpenItemDictiony)
{
if (item.Key == 1 || item.Key == 5 || item.Key == 8)
{
//为了排版方便,1,5,8加了样式,换行,调整padding的距离
<br /><label class="lableft"><input name="OpenItem" type="checkbox" value=@item.Key.ToString() />@item.Value </label>
}
else
{
<label><input name="OpenItem" type="checkbox" value=@item.Key.ToString() />@item.Value </label>
}
}
@Html.ValidationMessageFor(model => model.OpenItem, "", new { @class = "text-danger" })
</div>
遇到的问题,当勾选任意一个checkbox,只能选到第一个;当我故意填写相同日期时,调试代码 return View(ot); 大概提示OpenItem异常,如何正确使用Dictionary呈现checkbox,以便正确提交,有错误发生,正确返回绑定的checkbox!!!!!!