我有以下类:
public class Movie
{
string Name get; set;
string Director get; set;
IList<String> Tags get; set;
}如何绑定标记属性?转换为用逗号分隔的简单输入文本。但只对控制器I‘’am,对于孔应用程序不是。谢谢
发布于 2011-05-24 04:54:33
您可以从编写自定义模型绑定器开始:
public class MovieModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (propertyDescriptor.Name == "Tags")
{
var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if (values != null)
{
value = values.AttemptedValue.Split(',');
}
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}然后将其应用于应该接收输入的特定控制器操作:
public ActionResult Index([ModelBinder(typeof(MovieModelBinder))] Movie movie)
{
// The movie model will be correctly bound here => do some processing
}现在,当您发送以下GET请求时:
/index?tags=tag1,tag2,tag3&name=somename&director=somedirector或使用超文本标记语言<form>的POST请求
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
<div>
@Html.LabelFor(x => x.Director)
@Html.EditorFor(x => x.Director)
</div>
<div>
@Html.LabelFor(x => x.Tags)
@Html.TextBoxFor(x => x.Tags)
</div>
<input type="submit" value="OK" />
}Movie模型应该在控制器操作中正确绑定,并且仅在此控制器操作中绑定。
https://stackoverflow.com/questions/6102850
复制相似问题