我在ASP.NET MVC工作 我想在选择列表项上绑定一个值列表(我只发布相关代码)
型号:
public class Product
{
public int ProductId { get; set; }
public int SubcategoryId { get; set; }
public virtual Subcategory Subcategory { get; set; }
}
查看型号:
public class ProductViewModel
{
public int SelectedSubcategory { get; set; }
public IEnumerable <SelectListItem> Subcategory { get; set; }
}
获取控制器:
public ActionResult Create()
{
var subcategoryList = new ProductViewModel
{
Subcategory = new SelectList(db.ProductsList, "SubcategoryId", "Name")
};
return View(subcategoryList);
}
查看:
<div class="form-group">
@Html.LabelFor(model => model.SubcategoryId, "SubcategoryId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.SelectedSubcategory, Model.Subcategory, "-Select an option-", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SelectedSubcategory)
</div>
</div>
它没有约束价值的问题,我只得到强力打字“ - 选择一个选项 - ”,任何人都知道这里有什么问题?
----------------------------------------------- - - - - - - - - - - 编辑 - - - - - - - - - - - - - - - -------------------------------
现在我得到参数但是当我尝试创建产品时出错:
错误讯息:
INSERT语句与FOREIGN KEY约束“FK_dbo.Products_dbo.Subcategories_SubcategoryId”冲突。冲突发生在数据库“proyectname”,表“dbo.Subcategories”,列“SubcategoryId”中。 声明已经终止。
创建post方法:
public async Task<string> CreateProduct(ProductViewModel model)
{
var product = new Product
{
Name = model.Name,
Presentation = model.Presentation,
Image = model.Image,
Alt = model.Alt,
SubcategoryId = model.SelectedSubcategory,
IsDeleted = false
};
db.ProductsList.Add(product);
await db.SaveChangesAsync();
答案 0 :(得分:0)
试试这个:
public ActionResult Create()
{
Viewbag.SubcategoryId= new SelectList(db.ProductsList, "SubcategoryId", "Name")
return View();
}
<div class="form-group">
@Html.LabelFor(model => model.SubcategoryId, "SubcategoryId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("SubcategoryId", null, "-Select an option-", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SubcategoryId)
</div>
</div>