2017-05-10 100 views
1

我試圖將選擇列表中的選定項保存到我的數據庫,但由於某種原因,我的ID始終保持爲0。將選擇列表中的選定項保存到數據庫

這是視圖模型我使用:

public class ProductViewModel 
    { 
     #region Properties 

     [Required] 
     [Display(Name = "Naam")] 
     public string Name { get; set; } 

     [Required] 
     [Display(Name = "Type")] 
     public string Type { get; set; } 

     [Required] 
     [Display(Name = "Waarschuwing")] 
     public int WarningAmount { get; set; } 

     [Required] 
     [Display(Name = "Inkoopwaarde")] 
     public int Buy { get; set; } 

     [Required] 
     [Display(Name = "Verkoopwaarde")] 
     public int Sell { get; set; } 

     public int FactoryId { get; set; } 
     public SelectList FactoriesList { get; set; } 

     #endregion 
    } 

的觀點:

<div class="form-group"> 
      <label>Fabriek</label> 
      <select asp-for="FactoryId" asp-items="Model.FactoriesList"> 
       <option>Kies een fabriek</option> 
      </select> 
     </div> 

而在去年,我的控制器:

public async Task<IActionResult> Create() 
     { 
      ProductViewModel model = new ProductViewModel(); 

      var factories = _context.Factories.ToList(); 
      model.FactoriesList = new SelectList(factories, "FactoryId", "Name"); 

      return View(model); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public async Task<IActionResult> Post(
      [Bind("Name", "Type", "WarningAmount", "Buy", "Sell")] ProductViewModel model) 
     { 
      try 
      { 
       var config = new MapperConfiguration(cfg => cfg.CreateMap<ProductViewModel, Product>()); 
       var mapper = config.CreateMapper(); 
       Product product = mapper.Map<ProductViewModel, Product>(model); 

       product.Factory = _context.Factories.Where(w => w.FactoryId == model.FactoryId).First(); 

       _context.Products.Add(product); 
       await _context.SaveChangesAsync(); 
      } 
} 

所以,出於某種原因該model.FactoryId始終保持null。已經嘗試了很多,並且一直在努力幾個小時。

+0

您選擇並且您'發佈'並且在'發佈'行動中您總能找到'FactoryId'(即我s,'model.FactoryId')爲0.那是你在說什麼?如何在ViewModel(名稱,類型等)的其他項目?他們是否完全按照你輸入的內容來做? – Ian

回答

3

嘗試添加您在Post行動有Bind爲包括FactoryIdProductViewModel

[Bind("Name", "Type", "WarningAmount", "Buy", "Sell", "FactoryId")] 

此外,確保爲FactoryId比賽有怎樣的數據的數據類型(stringint)實際上輸入(例如,使用string爲下拉列表選項,而不是int

相關問題