【发布时间】:2014-02-08 08:56:40
【问题描述】:
我知道这个问题被问了很多次。我已阅读并实施了所有解决方案,但没有成功。当我使用 EF 从数据库中检索数据并在 View 上使用此模型后与模型绑定时,出现此错误。
我的控制器代码是
using System.Linq;
using System.Web.Mvc;
using JsonRenderingMvcApplication.Models;
namespace JsonRenderingMvcApplication.Controllers
{
public class PublisherController : Controller
{
public ActionResult Index()
{
PublisherModel model = new PublisherModel();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
model.PublisherList = context.Publishers.Select(x =>
new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
}); ;
}
return View(model);
}
}
}
我的查看代码是
@model JsonRenderingMvcApplication.Models.PublisherModel
@{
ViewBag.Title = "Index";
}
<div>
@Html.DisplayFor(model=>model.Id)
@Html.DropDownListFor(model => model.Id, Model.PublisherList);
</div>
<div id="booksDiv">
</div>
我的型号代码是
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace JsonRenderingMvcApplication.Models
{
public class PublisherModel
{
public PublisherModel()
{
PublisherList = new List<SelectListItem>();
}
[Display(Name="Publisher")]
public int Id { get; set; }
public IEnumerable<SelectListItem> PublisherList { get; set; }
}
}
我的实体代码是
namespace JsonRenderingMvcApplication.DAL
{
using System;
using System.Collections.Generic;
public partial class Publisher
{
public Publisher()
{
this.BOOKs = new HashSet<BOOK>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Year { get; set; }
public virtual ICollection<BOOK> BOOKs { get; set; }
}
}
是的,这个实体有一个导航属性,但我不想要那个实体数据,所以我不想包含它。
谢谢
【问题讨论】:
-
哪一行抛出异常?
-
@wdosanjos 这一行“@Html.DropDownListFor(model => model.Id, Model.PublisherList);”作为帖子标题引发异常
-
虽然与这个问题没有直接联系,但我发现同样的错误很有趣。我有这个 unitOfWork 类(具有 dbcontext 对象)和 ABC 类。 ABC 类通过 unitOfWork 类使用 dbContext 对象。 ABC 类和 unitOfWork 都通过温莎城堡 DI 容器实例化。我遇到了同样的错误,问题在于我在 DI 容器的初始化中注册类 ABC 的方式。我编写了类似 Register(Component.For
().ImplementedBy () .LifeStyle.Transient ) 的代码,但我错过了粗体代码,最终导致了这个问题。跨度>
标签: c# asp.net-mvc linq entity-framework dbcontext