[英]MVC custom model binder issue
I have a textbox in my view that i want to receive the value as a List of strings. 我在视图中有一个文本框,我希望以字符串列表的形式接收值。
As example, if anybody enters: tag1,tag2,tag3... receive a List with 3 elements. 例如,如果有人输入:tag1,tag2,tag3 ...接收一个包含3个元素的List。
I did a custom model binder, but im still receiving from the post the string instead the List. 我做了一个自定义模型绑定器,但我仍然从帖子接收字符串而不是List。
This is the stuff that i did: 这是我做的事情:
This is my Model: 这是我的模特:
public class BaseItem
{
[Required]
[StringLength(100)]
public string Name
{
get;
set;
}
public IList<string> RelatedTags
{
get;
set;
}
}
My typed view with the model above: 我上面的模型的类型视图:
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary("Please complete in a right way the fields below.") %>
<fieldset>
<legend>Fields</legend>
<div class="editor-field">
<%: Html.LabelFor(e => e.Name)%>
<%: Html.TextBoxFor(e => e.Name)%>
<%: Html.ValidationMessageFor(e => e.Name)%>
</div>
<div class="editor-field">
<%: Html.LabelFor(e => e.RelatedTags)%>
<%: Html.TextBoxFor(e => e.RelatedTags)%>
<%: Html.ValidationMessageFor(e => e.RelatedTags)%>
</div>
<p>
<input type="submit" />
</p>
</fieldset>
<% } %>
My custom model binder: 我的定制模型粘合剂:
public class TagModelBinder:DefaultModelBinder
{
protected override object GetPropertyValue(
ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor,
IModelBinder propertyBinder)
{
object value = base.GetPropertyValue(
controllerContext,
bindingContext,
propertyDescriptor,
propertyBinder);
object retVal = value;
if (propertyDescriptor.Name == "RelatedTags")
{
retVal = bindingContext.ValueProvider.GetValue("RelatedTags")
.RawValue.ToString().Split(',').ToList<string>();
}
return retVal;
}
}
I registered my Custom model binder on my Global.asax.cs file: 我在我的Global.asax.cs文件中注册了我的自定义模型绑定器:
ModelBinders.Binders.Add(typeof(string), new TagModelBinder());
The issue that im having is that never enters in the method "GetPropertyValue" of my custom binder. 我拥有的问题是永远不会进入我的自定义绑定器的方法“GetPropertyValue”。
For sure im missing anything. 当然我什么都没有。 Could you give me a hand? 你能帮我个忙吗?
Try binding to typeof IList as that is the type you are trying to bind too. 尝试绑定到IList类型,因为这也是您尝试绑定的类型。
ModelBinders.Binders.Add(typeof(IList<string>), new TagModelBinder());
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.