2016-06-09 115 views
1

我正在使用ASP.NET Core RC2 MVC與實體框架並試圖保存一輛新車。問題是,在汽車控制器的創建方法中,屬性顏色null當操作回發時。所有其他屬性/字段均已設置。但是指代CarColors模型的顏色爲空。ASP.NET核心MVC模型屬性綁定爲空

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

請求數據:

post request data張貼的汽車

debugging screenshot

調試截圖ü可以給我伸出援助之手,財產如何能夠被「綁定」等等ModelState.IsValid ==真

+1

莫非英語新我們如何請求? –

+0

儘管ASP.NET 5,這可能有助於https://lbadri.wordpress.com/2014/11/23/web-api-model-binding-in-asp-net-mvc-6-asp-net-5/ – Set

+0

添加了發佈請求數據的屏幕截圖。 –

回答

1

如果你想填充你的汽車模型的Color屬性,您的請求必須是這樣的:

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

這意味着:您輸入的名稱/選擇在視圖必須是「Color.CarColorId」。

...但你選擇了不正確的方式。您不應該直接在視圖中使用域模型。您應該爲視圖創建視圖模型,併爲您的動作方法的傳入屬性創建視圖模型。

正確的方式

域模型(不需改動):

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

感謝您的詳細信息!奇蹟般有效。 –

+0

因此,當使用ViewModel時,我們不能使用:[使用控制器保存功能中的參數綁定(「Color,Name,YearOfConstruction」)]'' ? – OmarBizreh