gpt4 book ai didi

c# - 如何在 DropDownFor 的 SelectList 中设置所选项目?

转载 作者:行者123 更新时间:2023-11-30 16:18:51 26 4
gpt4 key购买 nike

我是 MVC 的新手,但我已经通读了关于这个主题的几个问题。但是,没有一个答案可以解决我的问题。这是我的代码(只是相关的属性):

C# 类

public class Customer
{
public int CustomerId { get; internal set; }
public string Name { get; set; }
}

public class Project
{
public int ProjectId { get; internal set; }
public string Name { get; set; }
public string Description { get; set; }
public string Comment { get; set; }

public Customer CurrentCustomer { get; set; }
}

Controller 类

public ActionResult Edit(int id)
{
Project item = projectRepository.Get(id);

ViewBag.AllCustomers = new SelectList(
new CustomerRepository().Get(), // Returns a List<Customer> of all active customers.
"CustomerId",
"Name",
(object) item.CurrentCustomer.CustomerId);

return View(item);
}

查看

<div class="editor-label">
@Html.LabelFor(model => model.CurrentCustomer)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CurrentCustomer, (SelectList)ViewBag.AllCustomers, "-- Select a Customer. --")
@Html.ValidationMessageFor(model => model.CurrentCustomer)
</div>

我在不使用 ViewBag 的情况下尝试过此操作(在 View 本身中执行 SelectList 实例化),这也没有用。我试过对 ID 进行硬编码而不是使用 CurrentCustomer.CustomerId,但是当我在 SelectList 本身上设置断点时,我发现它正在正确处理所有内容。

所有其他 StackOverflow 问题都表明上述方法和属性名称应该可以正常工作,但对于我来说,我无法弄清楚这里出了什么问题。我错过了什么?

最佳答案

我怀疑您正在使用 EF Code-First。您犯的错误是试图将 int (id) 分配给实体 CurrentCustomerdropdownlist 只返回一个 id 而不是一个实体。

您应该将一个 Id 发送到您的操作方法,然后找到并分配实体(或者可以说只是外键)

在您的模型中添加一个 Id

public class Project
{
public int ProjectId { get; internal set; }
public string Name { get; set; }
public string Description { get; set; }
public string Comment { get; set; }

public Customer CurrentCustomer { get; set; }
public int CurrentCustomerId { get; set; }
}

在您看来

@Html.DropDownListFor(model => model.CurrentCustomerId,
(SelectList)ViewBag.AllCustomers, "-- Select a Customer. --")

关于c# - 如何在 DropDownFor 的 SelectList 中设置所选项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774998/

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