.net mvc razor dropdowns for foreign keys

2019-05-29 17:12发布

问题:

Ok, this seemed simple, but is making my head spin.

I have created models based on CodeFirst.

public class Category
{
    public int ID { get; set; }

    [StringLength(255, MinimumLength = 1)]
    public string Name { get; set; }
}

public class SubCategory
{
    public int ID { get; set; }
    public Category category { get; set; }

    [StringLength(255, MinimumLength = 1)]
    public string Name { get; set; }
}

Now when i auto-generate the controller and view for SubCategory it (out-of-the-box) lets me create new SubCategory objects without specifying the Category (even through it correctly creates a foreign key relation to the Category table in the DB).

So i though ok, i'll just drop a drop down in the create.cshtml file and have it use that.

after some while i succeed by adding this to the controller:

    public ActionResult Create()
    {
        ViewBag.Categories = new SelectList(db.Category.ToList(),"ID","Name");
        return View();
    } 

and this to the view:

    @Html.DropDownList(model => model.category, "Categories")

But now the object does not automatically catch that i want to use this for my foreign key, so when i stop the code at the POST method it still displays the object with NULL in the category field.

I guess my question is twofold. How should i do this? and if my method is right so far, what am i missing?

I just want the new object which is saved to the SubCategory table to include the foreign key to Category.

Hope this makes sense.

回答1:

Easiest way is to define a scalar property named CategoryId in your SubCategory class

public class SubCategory
{
    public int ID { get; set; }

    public int CategoryID { get; set; }
    public Category category { get; set; }

    [StringLength(255, MinimumLength = 1)]
    public string Name { get; set; }
}

Then correctly map it in EF

After that you put

@Html.DropDownListFor(
    model => model.CategoryID, category SelectList instance)
)

Other option is to create a custom model binder to bind Category type.