[英]ASP.NET Core MVC model property binding is null
我正在使用ASP.NET Core RC2 MVC与Entity Framework并尝试保存新车。 问题是,在汽车控制器的create方法中,当回发操作时,属性Color为null 。 所有其他属性/字段都已设置。 但引用CarColors模型的Color为null。
CarColor模型
public class CarColor
{
[Key]
public int CarColorId { get; set; }
[MinLength(3)]
public string Name { get; set; }
[Required]
public string ColorCode { get; set; }
}
主要车型
public class Car
{
[Key]
public int CarId { get; set; }
[MinLength(2)]
public string Name { get; set; }
[Required]
public DateTime YearOfConstruction { get; set; }
[Required]
public CarColor Color { get; set; }
}
汽车控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Color,Name,YearOfConstruction")] Car car)
{
if (ModelState.IsValid)
{
_context.Add(car);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(car);
}
请求数据:
调试已发布汽车的屏幕截图
你可以帮我一下,财产如何“绑定”,所以ModelState.IsValid == true ?
如果要填充Car模型的Color属性,则您的请求必须如下所示:
[0] {[Name, Volvo]}
[1] {[Yearof Construction, 19/16/2015]}
[2] {[Color.CarColorId, 3]} (will be "bound" only ID)
这意味着:View上的输入/选择名称必须为“Color.CarColorId”。
......但你选择了不正确的方法。 您不应直接在视图中使用域模型。 您应该为View以及您的操作方法的传入属性创建特殊的视图模型。
正确的方法
域模型(无变化):
public class CarColor
{
[Key]
public int CarColorId { get; set; }
[MinLength(3)]
public string Name { get; set; }
[Required]
public string ColorCode { get; set; }
}
public class Car
{
[Key]
public int CarId { get; set; }
[MinLength(2)]
public string Name { get; set; }
[Required]
public DateTime YearOfConstruction { get; set; }
[Required]
public CarColor Color { get; set; }
}
查看型号:
public class CarModel
{
[MinLength(2)]
public string Name { get; set; }
[Required]
public DateTime YearOfConstruction { get; set; }
[Required]
public int ColorId { get; set; }
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CarModel model)
{
if (ModelState.IsValid)
{
var color = await _context.Colors.FirstAsync(c => c.CarColorId == model.ColorId, this.HttpContext.RequestAborted);
var car = new Car();
car.Name = model.Name;
car.YearOfConstruction = model.YearOfConstruction;
car.Color = color;
_context.Cars.Add(car);
await _context.SaveChangesAsync(this.HttpContext.RequestAborted);
return RedirectToAction("Index");
}
return View(car);
}
在我的情况下,我在我的模型类上有自动生成的internal set
属性。 框架不能绑定那些。 也许这篇文章将来会帮助某人,因为我花了一段时间来弄清楚这一点;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.