2017-05-10 85 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

相关问题