更新:這在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;
}
}