【发布时间】:2011-02-10 21:23:47
【问题描述】:
我正在尝试创建一个视图模型并添加一个 SelectListItem 以允许我绑定一个下拉列表。 我有一个非常基本的视图模型,看起来像这样
public class CreatePurchaseViewModel
{
public Product Product { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public int SelectedProductId { get; set; }
public DateTime OrderDate { get; set; }
public bool OrderSent { get; set; }
}
我的控制器是这样的
[HttpGet]
public ActionResult Create()
{
var model = new CreatePurchaseViewModel
{
Products = context.Products.Select(x =>
new SelectListItem()
{
Text = x.ProductName,
Value = x.ProductID
})
};
return View(model);
}
但是它抱怨 Value = x.Product 无法将 int 类型转换为字符串。因此,如果我添加一个 .ToString 它可以编译,但是当我尝试加载视图时出现错误
LINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式。
我的观点
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CreatePurchaseViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.SelectedProductId)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.SelectedProductId,Model.Products)
@Html.ValidationMessageFor(model => model.SelectedProductId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.OrderDate)
</div>
<div class="editor-field">
@Html.TextBoxFor(model=>model.OrderDate)
@Html.ValidationMessageFor(model => model.OrderDate)
</div>
<div>
Sent
@Html.RadioButtonFor(model => model.OrderSent, "Sent", new { @checked = true })
Not Sent
@Html.RadioButtonFor(model=>model.OrderSent,"Not Sent")
我对实体框架和 mvc 都很陌生,所以任何帮助都会很棒。
谢谢
【问题讨论】:
标签: entity-framework asp.net-mvc-3