2012-06-28 48 views
1

我有一个包含的标签列表的申请人型号:ASP.NET MVC3自定义模型绑定问题

public class Applicant 
{ 
    public virtual IList<Tag> Tags { get; protected set; } 
} 

当提交表单时,有一个包含逗号分隔的标签列表的输入域用户有输入。我有一个自定义的模型绑定到这个列表转换为一个集合:

public class TagListModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var incomingData = bindingContext.ValueProvider.GetValue("tags").AttemptedValue; 
     IList<Tag> tags = incomingData.Split(',').Select(data => new Tag { TagName = data.Trim() }).ToList(); 
     return tags; 
    } 
} 

然而,当我的模型填充并传递到上POST控制器动作,标签属性仍是一个空列表。任何想法为什么它没有正确填充列表?

+0

http://prideparrot.com/blog/archive/2012/6/customizing_property_binding_through_attributes – VJAI

+0

@马克我没有看到一个理由更换整个模型粘合剂作为你的链接可能会建议。 –

+0

请检查我的答案 – VJAI

回答

2

的问题是你有Tags财产protected set访问。如果您将其更改为public,则下面的内容可以正常工作。

public class Applicant 
{ 
    public virtual IList<Tag> Tags { get; set; } 
} 
2

模型联编程序仅绑定提交的值。它不绑定在视图中呈现的值。

您需要创建一个自定义EditorTemplate来根据需要呈现标记。

1

MVC可以already bind to a List,我会建议使用内置的技术,已经做到了你所需要的。

我没有注意到有关添加活页夹的任何代码,您是否将ModelBinder添加到活页夹中?

protected void Application_Start() 
{ 
    ModelBinders.Binders.Add(typeof(IList<Tag>), new TagListModelBinder()); 
} 
+0

是的,我确实将它添加到活页夹中,并被调用。它只是不会填充在action方法参数中。 – arknotts

+0

我看着你的链接绑定到列表。不幸的是,这在我的场景中不起作用,因为我在客户端使用的JavaScript将所有内容放入一个输入字段。 – arknotts