gpt4 book ai didi

entity-framework-4 - 从 db 填充下拉列表

转载 作者:行者123 更新时间:2023-12-01 09:07:44 26 4
gpt4 key购买 nike

我的 Entity Framework 中有一个带有 2 个表的 mvc 3 应用程序。

PurchaseTable 是 PurchaseID、PurchaseDate 和 ProductID 我有另一个名为 Product 的表,其中包含 ProductID 和 ProductName。创建新 View 以插入新购买 如何将 View 中 ProductID 的文本框更改为由 Product 表中 ProductName 绑定(bind)的下拉列表?

最佳答案

创建一个 ViewModel:

public class CreatePurchaseViewModel
{
public Purchase Purchase { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public int SelectedProductId { get; set; }
}

使用 ViewModel 设置 View :

[HttpGet]
public ActionResult CreateProduct()
{
var model = new CreatePurchaseViewModel
{
Products = repository.FindAllProducts().Select(x =>
new SelectListItem
{
Text = x.ProductName,
Value = x.ProductId
}
};

return View(model);
}

然后简单地绑定(bind)到 ViewModel 并使用 DropDownListFor HTML Helper:

<! -- other code to bind to Purchase, and then: -->

<%= Html.DropDownListFor(x => x.SelectedProductId, Model.Products) %>

然后当您提交表单时,模型中的 SelectedProductId 值将使用下拉列表中的选定值填充。

关于entity-framework-4 - 从 db 填充下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4827243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com