ASP.NET EditorTemplate DropdownList
Asked Answered
C

3

9

Every time I add a new App It creates a new AppCategory. I am seriously screwing this up somehow

code first entity framework objects

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

Editor Template (I would love to just make just one Foreign Key EditorTemplate)

@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("Category", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())

and of course the repository

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

Every time I add a new App It creates a new AppCategory I am seriously screwing this up somehow


Adding more debug info
 @inherits System.Web.Mvc.WebViewPage
 @Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())

gives me a validation message on the post

 Parameters  application/x-www-form-urlencoded
 Category   1
 Name   8

Validation error The value '1' is invalid.
This makes sense because Category should be an object not an integer.


Controller Code as asked for pretty sure this isnt the problem as it came from MVCScaffold

    [HttpPost]
    public ActionResult Create(App d)
    {
        if (ModelState.IsValid)
        {
          context.Apps.Add(d);
          context.SaveChanges();
          return RedirectToAction("Index");  
        }
        return View();
     }
Chaldea answered 15/11, 2010 at 20:31 Comment(3)
I have no idea what your question is or how you got an upvote for article. Have you stepped through the program in a debugger to narrow down where whatever your problem is occurs?Diplopod
from the controller [HttpPost] public ActionResult Create(App d) I get d.Category is null (thats why its creating a new one) but i dont know why i get d.Category is nullChaldea
Post your controller code please. I'm fairly certain the problem is there.Misteach
C
5

My model was incorrectly set up ... virtual ICollection and just the foreign key id for the sub and everything worked... changes below

Model

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();
    }
Chaldea answered 19/11, 2010 at 16:3 Comment(0)
Q
0

If you bind your dropDownList to Category.Id, you'll at least get the selected value into that filed, but nothing else in your Category Object.

Quadrille answered 16/11, 2010 at 16:58 Comment(1)
It still tries to create a new Category objectChaldea
E
0

The model binder cannot create the AppCategory object from the form collection in your Create action because the form only has an ID for that object (the other properties of AppCategory are not there).

The quickest solution would be setting the Category property of your App object manually, like this :

[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();
 }
Equity answered 19/11, 2010 at 4:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.