我正在使用角度服务将数据发布到Webapi,操作正在执行,并且我正在接收除DepartmentName
json数组以外的所有数据。从前端,我正在传递DepartmentName
和其他数据的json数组,如您在所附图像中看到的,但我没有得到DepartmentName
json数组的实际作用。我还传递了一个文件,我也正在行动,但仅针对DepartmentName
json数组存在问题。我正在尝试从最近2天开始解决此问题,但我无法解决。我希望您能理解我的问题。为进一步解释,我还附上了表格数据和代码的图片。
模型
public class UserViewModel
{
public string fullName { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string email { get; set; }
[Column(TypeName = "nvarchar(20)")]
public string phone { get; set; }
[Column(TypeName = "nvarchar(15)")]
public string gender { get; set; }
[Column(TypeName = "nvarchar(20)")]
public string dateOfBirth { get; set; }
[Column(TypeName = "nvarchar(200)")]
public string address { get; set; }
[Column(TypeName = "nvarchar(max)")]
public string password { get; set; }
[Column(TypeName = "nvarchar(max)")]
public string userImageName { get; set; }
public List<Department> DepartmentName { get; set; }
}
public class Department
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DepartmentID { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string DepartmentName { get; set; }
public virtual ICollection<UserDepartment> UserDepartments { get; set; }
}
Controller
[HttpPost, Route("[action]")]
public async Task<IActionResult> AddNewUser([FromForm] UserViewModel userViewModel )
{
//other coding here
return Ok()
}
Angular
<mat-form-field class="example-full-width">
<mat-select placeholder="Select department(s)" formControlName="DepartmentName" multiple>
<mat-option *ngFor="let department of departmentList" [value]="department">{{department.departmentName}}</mat-option>
</mat-select>
</mat-form-field>
来自网络的表单数据
操作已执行,我正在接收数据,除DepartmentName json数组之外的所有数据
基于模型类,将表单值正确绑定到模型,您可以尝试以下方法:
方法1:在有角度的客户端上,为List<Department> DepartmentName
属性生成表单数据,如下所示。
方法2:实现自定义模型绑定程序,以获取您传递的DepartmentName json数组并将其反序列化为List<Department>
。
[ModelBinder(BinderType = typeof(DepartmentNameModelBinder))]
public List<Department> DepartmentName { get; set; }
DepartmentNameModelBinder类
public class DepartmentNameModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// ...
// implement it based on your actual requirement
// code logic here
// ...
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var model = JsonSerializer.Deserialize<List<Department>>(bindingContext.ValueProvider.GetValue("DepartmentName").FirstOrDefault(), options);
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
测试结果