您可以创建自定义模型绑定器来绑定字符串数组,如下所示:
public class StringArrayBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string key = bindingContext.ModelName;
ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val != null && string.IsNullOrEmpty(val.AttemptedValue) == false)
{
bindingContext.ModelState.SetModelValue(key, val);
string incomingString = ((string[])val.RawValue)[0];
var splitted = incomingString.Split(',');
if (splitted.Length > 1)
{
return splitted;
}
}
return null;
}
}
然后在应用程序启动时注册它global.asax
:
ModelBinders.Binders[typeof(string[])] = new StringArrayBinder();
甚至更简单但可重用性较低的方法是:
public string[] MyStringPropertyArray { get; set; }
public string MyStringProperty
{
get
{
if (MyStringPropertyArray != null)
return string.Join(",", MyStringPropertyArray);
return null;
}
set
{
if (!string.IsNullOrWhiteSpace(value))
{
MyStringPropertyArray = value.Split(',');
}
else
{
MyStringPropertyArray = null;
}
}
}
在这里,您将绑定到MyStringProperty
视图中。然后在您的业务代码中使用MyStringPropertyArray
(填充来自 的值)。MyStringProperty