我如何使用 ASP.NET MVC UpdateModel 执行以下操作?我正在尝试将空格分隔的文本框数据(与新的 StackOverflow 问题中的 TAGS 文本框完全相同,例如这个)读入模型中。
eg.
<input type="Tags" type="text" id="Tags" name="Tags"/>
...
public class Question
{
public string Title { get; set; }
public string Body { get; set; }
public LazyList<string> Tags { get; set; }
}
....
var question = new Question();
this.UpdateModel(question, new [] { "Title", "Body", "Tags" });
Tags 属性确实被实例化,但它只包含一项,即输入到 Tags 输入字段的全部数据。如果我想在列表中包含单个项目(基于通过空格分割字符串)..处理这个问题的最佳实践是什么?
cheers!
您需要做的是将 DefaultValueProvider 扩展为您自己的。在您的值提供程序中,扩展 GetValue(name) 以拆分标签并加载到您的 LazyList 中。您还需要更改对 UpdateModel 的调用:
UpdateModel(q, new[] { "Title", "Body", "Tags" },
new QuestionValueProvider(this.ControllerContext));
我写的 QuestionValueProvider 是:
public class QuestionValueProvider : DefaultValueProvider
{
public QuestionValueProvider(ControllerContext controllerContext)
: base(controllerContext)
{
}
public override ValueProviderResult GetValue(string name)
{
ValueProviderResult value = base.GetValue(name);
if (name == "Tags")
{
List<string> tags = new List<string>();
string[] splits = value.AttemptedValue.Split(' ');
foreach (string t in splits)
tags.Add(t);
value = new ValueProviderResult(tags, null, value.Culture);
}
return value;
}
}
希望这可以帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)