mvc html.checkbox,如何在ASP.NET MVC中維護Html.CheckBox()的狀態

更新:這在RC2中已修復。

This question together with this one,

這個問題和這一個一起,

addresses a very undocumented feature of the ASPNET.MVC RC1. I have been searching around for hours to find a good answer, but there are very few to find.

解決了ASPNET.MVC RC1的一個非文檔特征。我一直在尋找好幾個小時找到一個好的答案,但很少有人找到。

There is a bug, apparently, which prohibit checkboxes and radiobuttons to maintain their state from ModelState. As we also know by now, is that these two controls are handled specially by the Html helpers.

顯然,有一個錯誤禁止復選框和單選按鈕從ModelState維護其狀態。我們現在也知道,這兩個控件是由Html助手專門處理的。

The best I managed to come up with, was to build my own ViewBinder:

我設法得到的最好的,就是構建我自己的ViewBinder:

From a very simple view:

從一個非常簡單的看法:

Keep checkbox value between posts

Associated with an equally simple controller:

與同樣簡單的控制器相關聯:

public class CheckboxController : Controller

{

public ActionResult Index()

{

return View();

}

public ActionResult Update()

{

var binder = new ViewBinder(ViewData, ValueProvider);

binder.UpdateBooleanValues("a", "b");

binder.UpdateMissingValues();

return View("Index");

}

}

And a simple class to make it all work:

還有一個簡單的類可以使它全部工作:

internal class ViewBinder

{

private readonly IDictionary valueProvider;

private readonly ViewDataDictionary viewData;

public ViewBinder(ViewDataDictionary viewData, IDictionary valueProvider)

{

this.valueProvider = valueProvider;

this.viewData = viewData;

}

public void UpdateMissingValues()

{

foreach (var key in valueProvider.Keys)

{

if (ValueIsMissing(key)) UpdateValue(key);

}

}

public void UpdateBooleanValues(params string[] names)

{

foreach (var name in names)

{

UpdateValue(name, BooleanValueFor(name));

}

}

private bool BooleanValueFor(string name)

{

return valueProvider[name].AttemptedValue != "false";

}

private bool ValueIsMissing(string key)

{

return viewData.ContainsKey(key) == false;

}

private void UpdateValue(string key)

{

var value = valueProvider[key].AttemptedValue;

UpdateValue(key, value);

}

private void UpdateValue(string key, object value)

{

viewData[key] = value;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值