实现模型绑定器以绑定某种数据格式

时间:2011-06-07 15:51:51

标签: asp.net-mvc

我想模拟绑定此客户端发送的数据

tag[15-d] : Little Owl
tag[19-a] : Merlin

name : value

进入IEnumrable<AutoCompleteItem>

public class AutoCompleteItem
{
  public string Key { get; set; }
  public string Value { get; set; }
}

例如

Key = 15-d
Value = Little Owl

我不知道如何在这种情况下实现我自己的模型绑定器,任何解决方案?

2 个答案:

答案 0 :(得分:1)

这是我为你做的模型活页夹,并做你想要的。它绝不是完整的(没有验证,没有错误检查等),但它可以启动你。我特别不喜欢的一件事是,ModelBinder直接访问表单集合而不是使用上下文的ValueProvider,但后者不允许您获取所有可绑定值。

public class AutoCompleteItemModelBinder : IModelBinder
{
    // Normally we would use bindingContext.ValueProvider here, but it doesn't let us
    // do pattern matching.
    public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string pattern =  @"tag\[(?<Key>.*)\]";
        if (!String.IsNullOrWhiteSpace (bindingContext.ModelName))
            pattern = bindingContext.ModelName + "." + pattern;

        IEnumerable<string> matchedInputNames = 
            controllerContext.HttpContext.Request.Form.AllKeys.Where(inputName => Regex.IsMatch(inputName, pattern, RegexOptions.IgnoreCase));

        return matchedInputNames.Select (inputName =>
            new AutoCompleteItem {
                Value = controllerContext.HttpContext.Request.Form[inputName],
                Key = Regex.Match(inputName, pattern).Groups["Key"].Value
            }).ToList();
    }
}

以下是使用它的示例操作:

[HttpPost]
public void TestModelBinder ([ModelBinder(typeof(AutoCompleteItemModelBinder))]
                             IList<AutoCompleteItem> items)
{
}

示例视图。注意“项目”。前缀 - 它是模型名称(您可以根据提交此项目列表的方式删除它:

@using (Html.BeginForm ("TestModelBinder", "Home")) {
    <input type="text" name="items.tag[15-d]" value="Little Owl" />
    <input type="text" name="items.tag[19-a]" value="Merlin" />
    <input type="submit" value="Submit" />
}

如果您有疑问 - 请添加评论,我会扩展此答案。

答案 1 :(得分:0)

你应该只能命名你的字段键[0],值[0](1,2,3等),它应该自动绑定,因为它们只是字符串。如果由于某种原因需要自定义它 - 仍然将字段命名为键[0]值[0](然后是1,2,3等)并完全按照此处的指定执行: ASP.NET MVC - Custom model binder able to process arrays