ASP.NET Core MVC model property binding is null

ぐ巨炮叔叔 提交于 2019-12-04 19:39:36

If you want populate Color property of your Car model, your request must looks like:

[0] {[Name, Volvo]}
[1] {[Yearof Construction, 19/16/2015]}
[2] {[Color.CarColorId, 3]} (will be "bound" only ID)

It means: name of your input/select on the View must be "Color.CarColorId".

... But you chose incorrect way. You should not use Domain models in your View directly. You should create View Models special for View and for incoming properties of you action methods.

correct way

domain models (without changes):

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

View model:

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

In my case I had auto generated internal set properties on my model class. Framework couldn't bind those. Maybe this post will help someone in future as it took me a while to figure this out ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!