我正在尝试将 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
}
View :
<div class="form-group">
<label>Fabriek</label>
<select asp-for="FactoryId" asp-items="Model.FactoriesList">
<option>Kies een fabriek</option>
</select>
</div>
最后,我的 Controller :
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
。已经尝试了很多,并且挣扎了几个小时。
最佳答案
尝试在 Post
操作中添加 Bind
以包含 ProductViewModel
中的 FactoryId
:
[Bind("Name", "Type", "WarningAmount", "Buy", "Sell", "FactoryId")]
此外,确保 FactoryId
的数据类型(string
或 int
)与数据的实际输入方式相匹配(例如,使用 string
作为下拉列表选项而不是 int
)
关于c# - 将 SelectList 中的选定项保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43888590/