在某些特殊情况下,您将需要一个文本框列表(用于处理 n - n 个关联),其 id 在运行前是未知的。像这样的东西: http: //screencast.com/t/YjIxNjUyNmU
在那个特定的示例中,我希望将计数与我的一些“模板”相关联。
在ASP.Net MVC 1中,我编写了一个 Dictionary ModelBinder 以获得干净直观的 HTML。它允许这样的事情:
// loop on the templates
foreach(ITemplate template in templates)
{
// get the value as text
int val;
content.TryGetValue(template.Id, out val);
var value = ((val > 0) ? val.ToString() : string.Empty);
// compute the element name (for dictionary binding)
string id = "cbts_{0}".FormatMe(template.Id);
%>
<input type="text" id="<%= id %>" name="<%= id %>" value="<%= value %>" />
<label for="<%= id %>"><%= template.Name %></label>
<br />
这是活页夹的代码:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
IDictionary<int, int> retour = new Dictionary<int, int>();
// get the values
var values = bindingContext.ValueProvider;
// get the model name
string modelname = bindingContext.ModelName + '_';
int skip = modelname.Length;
// loop on the keys
foreach(string keyStr in values.Keys)
{
// if an element has been identified
if(keyStr.StartsWith(modelname))
{
// get that key
int key;
if(Int32.TryParse(keyStr.Substring(skip), out key))
{
int value;
if(Int32.TryParse(values[keyStr].AttemptedValue, out value))
retour.Add(key, value);
}
}
}
return retour;
}
传递给ASP.Net MVC 2时,问题是ValueProvider不再是字典。没有办法像我一样循环遍历这些值来解析它们。
而且我没有找到任何其他方法(如果您知道,请告诉我)。
我终于切换到绑定字典的“标准”方式,但 HTML 很丑陋,违反直觉(使用计数器循环非索引集合??)并且所有值都是必需的,这与我需要的行为不同(而且在 ASP.Net MVC 1) 中完美运行。
它看起来像这样:
int counter= 0;
// loop on the templates
foreach(ITemplate template in templates)
{
// get the value as text
int val;
content.TryGetValue(template.Id, out val);
var value = ((val > 0) ? val.ToString() : string.Empty);
// compute the element name (for dictionary binding)
string id = "cbts_{0}".FormatMe(template.Id);
string dictKey = "cbts[{0}].Key".FormatMe(counter);
string dictValue = "cbts[{0}].Value".FormatMe(counter++);
%>
<input type="hidden" name="<%= dictKey %>" value="<%= template.Id %>" />
<input type="text" id="<%= id %>" name="<%= dictValue %>" value="<%= value %>" />
<label for="<%= id %>"><%= template.Name %></label>
<br />
在控制器中,我需要欺骗ModelState
以避免“需要值”错误:
public ActionResult Save(int? id, Dictionary<int, int> cbts)
{
// clear all errors from the modelstate
foreach(var value in this.ModelState.Values)
value.Errors.Clear();
这太棘手了。我很快将需要多次使用这种绑定,并且可能需要一些层级的开发人员在应用程序上工作。
问题 :
- 你知道一种让它变得更好的方法吗?
IMO,我需要的是一个用于字典的 ModelBinder,它允许更好的 html 并且不考虑所有值都是必需的。