我已在 Program.cs 文件中全局启用自定义人物模型绑定器
但是如何从请求正文中检索标签列表中的值并将它们手动分配给 person.Tags 列表?
所以这基本上是自定义模型类提供程序和集合绑定的组合。
您的自定义模型绑定几乎是正确的,您的标签绑定可能存在一些错误。这是一个示例。
PersonModelBinder
public class PersonModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var person = new Person();
//Other properties
//…
// Bind the Tags property
var values = bindingContext.ValueProvider.GetValue("Tags").Values;
var tags = new List<string>();
foreach (var value in values)
{
if (!string.IsNullOrEmpty(value))
{
tags.Add(value.Trim());
}
}
person.Tags = tags;
bindingContext.Result = ModelBindingResult.Success(person);
return Task.CompletedTask;
}
}
PersonModelBinderProvider
public class PersonModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(Person))
{
return new BinderTypeModelBinder(typeof(PersonModelBinder));
}
return null;
}
}
控制器
[HttpPost]
public IActionResult CreatePerson([ModelBinder(BinderType = typeof(PersonModelBinder))] Person person)
{
if (ModelState.IsValid)
{
return RedirectToAction("Success");
}
return View(person);
}
public IActionResult Create()
{
return View();
}
创建视图
@model Person
@{
ViewData["Title"] = "Create Person";
}
<h2>@ViewData["Title"]</h2>
<form asp-action="CreatePerson" method="post">
@*other properties*@
<div>
<label>Tags:</label>
<input type="text" name="Tags" value="" placeholder="Enter tag1" />
<input type="text" name="Tags" value="" placeholder="Enter tag2" />
<input type="text" name="Tags" value="" placeholder="Enter tag3" />
<span asp-validation-for="Tags"></span>
</div>
<button type="submit">Create</button>
</form>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}