【问题标题】:ASP.NET EditorTemplate DropdownListASP.NET 编辑器模板下拉列表
【发布时间】:2011-05-10 11:11:25
【问题描述】:

每次我添加一个新应用都会创建一个新的 AppCategory。我以某种方式严重搞砸了这个

代码优先实体框架对象

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; }
}

编辑器模板(我只想制作一个外键 EditorTemplate)

@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 应该是一个对象而不是整数。


要求的控制器代码 很确定这不是问题,因为它来自 MVCScaffold

    [HttpPost]
    public ActionResult Create(App d)
    {
        if (ModelState.IsValid)
        {
          context.Apps.Add(d);
          context.SaveChanges();
          return RedirectToAction("Index");  
        }
        return View();
     }

【问题讨论】:

  • 我不知道您的问题是什么,也不知道您是如何为文章点赞的。您是否已在调试器中逐步检查程序以缩小出现问题的位置?
  • 从控制器 [HttpPost] public ActionResult Create(App d) 我得到 d.Category 为空(这就是它创建新的原因)但我不知道为什么我得到 d.Category 为空
  • 请发布您的控制器代码。我很确定问题就在那里。

标签: asp.net-mvc asp.net-mvc-2 editortemplates


【解决方案1】:

我的模型设置不正确...虚拟 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())

应用控制器

 [HttpPost]
    public ActionResult Create(App d)
    {
        if (ModelState.IsValid)
        {
          this.repository.Add(d);
          this.repository.Save();
          return RedirectToAction("Index");  
        }
        return View();
    }

【讨论】:

    【解决方案2】:

    模型绑定器无法从您的 Create 操作中的表单集合创建 AppCategory 对象,因为表单只有该对象的 ID(AppCategory 的其他属性不存在)。

    最快的解决方案是手动设置App 对象的Category 属性,如下所示:

    [HttpPost]
    public ActionResult Create(App d) {
        int categoryId = 0;
        if (!int.TryParse(Request.Form["Category"] ?? String.Empty, out categoryId) {
            // the posted category ID is not valid
            ModelState.AddModelError("Category", 
                "Please select a valid app category.")
        } else {
            // I'm assuming there's a method to get an AppCategory by ID.
            AppCategory c = context.GetAppCategory(categoryID);
            if (c == null) {
                // couldn't find the AppCategory with the given ID.
                ModelState.AddModelError("Category", 
                    "The selected app category does not exist.")
            } else {
                // set the category of the new App.
                d.Category = c;
            }
        }
        if (ModelState.IsValid)
        {
          context.Apps.Add(d);
          context.SaveChanges();
          return RedirectToAction("Index");  
        }
        return View();
     }
    

    【讨论】:

      【解决方案3】:

      如果您将 dropDownList 绑定到 Category.Id,您至少会将选定的值放入该字段,但不会在您的 Category 对象中获得任何其他值。

      【讨论】:

      • 它仍然尝试创建一个新的 Category 对象
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多