作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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) 分配给实体 CurrentCustomer
。 dropdownlist
只返回一个 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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!