Dropdown list better as ViewBag or part of model C

2019-02-12 23:32发布

问题:

Probably simple, but I seem to be missing something.

Two Models:

public class Hardware
{
    [Required]
    public int Id { get; set; }

    public int SerialNum { get; set; }
    public int ProductNum { get; set; }
    public string Notes { get; set; }
    public DateTime PurchaseDate { get; set; }
    public DateTime WarrantyExpiration { get; set; }

    public virtual Manufacturer Manufacturer { get; set; }
}

public class Manufacturer
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<Hardware> Hardware { get; set; }
}

When I go to the Hardware Create view, I want to to be able to select from a dropdown of Manufacturers, and when it submits it should establish a relationship between the piece of hardware and the select Manufacturer.

At the moment, I've been using the following to build a selectList in the controller

SelectList selectList = new SelectList(db.Manufacturers, "Id", "Name");
ViewBag.selectList = selectList;

And then casting it in the view:

@Html.DropDownListFor(model => model.Manufacturer, ViewBag.selectList as SelectList)\

However, it seems like there should be a better way to do this - perhaps creating a viewModel that inherits from Hardware with a SelectList typed property?

回答1:

As your application gets more and more complicated, you will see your MVC application turning into M-VM-V-C, VM is dedicated ViewModels that usually adds all the things that your UI layer need in order to generate the UI.

I personally wouldn't go with inheritance in this case, because your ViewModel is not a specialized version of your Model. It's just what your UI need to create a View (this is really up to you).

My ViewModel would look something like this:

public class HardwareVm
{
     public Hardware Hardware { get; set; }
     public IEnumerable<SelectListItem> Manufacturers { get; set; }
} 

in the View:

@Html.DropDownListFor(model => model.Hardware.Manufacturer,  Manufacturers)

controller:

var manufacturers = db.Manufacturers.Select(m => new SelectListItem {Text = m.Name, Value = m.Id });
var model = new HardwareVm { Manufacturers = manufacturers };