gpt4 book ai didi

c# - ASP.NET Core MVC 模型属性绑定(bind)为空

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:29 25 4
gpt4 key购买 nike

我正在将 ASP.NET Core RC2 MVC 与 Entity Framework 结合使用,并试图挽救一辆新车。问题是,在汽车 Controller 的创建方法中,回发操作时属性 Colornull。设置所有其他属性/字段。但是引用 CarColors 模型的 Color 为空。

CarColor 模型

public class CarColor
{
[Key]
public int CarColorId { get; set; }

[MinLength(3)]
public string Name { get; set; }

[Required]
public string ColorCode { get; set; }
}

主要车型Car

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; }
}

汽车 Controller

[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);
}

请求数据:

post request data

调试贴车截图

debugging screenshot

你能帮帮我吗,如何“绑定(bind)”属性等等 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 中使用领域模型。您应该为 View 和操作方法的传入属性创建专门的 View Models。

正确的方法

领域模型(没有变化):

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; }
}

Controller :

[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);
}

关于c# - ASP.NET Core MVC 模型属性绑定(bind)为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com