我正在尝试将SelectList中的选定项目保存到我的数据库中,但由于某种原因,我的ID始终保持为“0”。
这是我正在使用的ViewModel:
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 :(得分:3)
尝试在Bind
操作中添加Post
,以包含FactoryId
中的ProductViewModel
:
[Bind("Name", "Type", "WarningAmount", "Buy", "Sell", "FactoryId")]
另外,请确保FactoryId
的数据类型与数据的实际输入方式匹配(string
或int
)(例如,使用string
进行下拉列表列表选项而不是int
)