每次添加新App时,它都会创建一个新AppCategory 。我正在以某种方式认真解决这个问题
编码第一个 Entity Framework 对象
public class AppCategory
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<App> apps { get; set; }
}
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public AppCategory Category { get; set; }
}
编辑器模板(我只想制作一个外键编辑器模板)
@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("Category", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
当然还有仓库
public static IEnumerable<SelectListItem> GetAppCategoriesSelect()
{
return (from p in GetAppCategories()
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString(),
});
}
public static ICollection<AppCategory> GetAppCategories()
{
var context = new LIGDataContext();
return context.AppCategories.ToList();
}
每当我添加一个新的应用程序它创建一个新的AppCategory时,我都会以某种方式认真解决这个问题
添加更多调试信息
@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
在帖子上给了我一条验证消息
Parameters application/x-www-form-urlencoded
Category 1
Name 8
验证错误值“1”无效。
这是有道理的,因为Category应该是不是整数的对象。
要求的 Controller 代码
很确定这不是问题,因为它来自MVCScaffold
[HttpPost]
public ActionResult Create(App d)
{
if (ModelState.IsValid)
{
context.Apps.Add(d);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
最佳答案
我的模型设置不正确...虚拟ICollection以及该子对象的外键ID,一切正常...下面进行了更改
模型
public class AppCategory
{
public int ID { get; set; }
public string Name { get; set; }
public **virtual** ICollection<App> Apps { get; set; }
}
public class App
{
public int ID { get; set; }
********************************************
[UIHint("AppCategory")]
public int AppCategoryID { get; set; }
********************************************
public string Name { get; set; }
}
public class LIGDataContext : DbContext
{
public DbSet<AppCategory> AppCategories { get; set; }
public DbSet<App> Apps { get; set; }
}
/Views/Shared/EditorTemplates/AppCategory.cshtml
@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
AppController
[HttpPost]
public ActionResult Create(App d)
{
if (ModelState.IsValid)
{
this.repository.Add(d);
this.repository.Save();
return RedirectToAction("Index");
}
return View();
}
关于asp.net-mvc - ASP.NET EditorTemplate下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188525/