简体   繁体   中英

Dropdownlist on Asp.net MVC 3 from viewModel

I have a model. This model look like this:

public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public List<Category> Parent { get; set; }

In the add action I populate Parent:

public ViewResult Add()
{
    var addCategoryModel = new CategoryEditModel
    {
        Parent = Mapper.Map<List<Category>>(_productRepository.Categories.ToList())
    };
    return View("add", addCategoryModel);
}

When I submit the form my model state always is invalid, because my selected value in DropDownList "..is invalid." I made something wrong. What is the correct way to do this?

I've had some hard times with drop downs and helpers for them in MVC too. I finally have adopted the following approach as my way:

In my view model I create:

public List<SelectListItem> employeeList;
public int SelectedItemID;

Typically would have a get for populating the drop down via the database/Entity Framework:

public IEnumerable<SelectListItem> employeeList
    {
        get
        {
            return new SunGardDBEntities()
                .employees
                .OrderBy(e => e.employeeFName)
                .ToList()
                .Select(e => new SelectListItem { Text = e.employeeFName + " " + e.employeeLName, Value = e.employeeID.ToString() });
        }
    }

And in my .cshtml file I then say:

@Html.DropDownListFor(model => model.SelectedItemID, new SelectList(Model.employeeList, "Value", "Text"), new Dictionary<string, object> { { "data-placeholder", "Choose a sandbox..." }, { "class", "chzn-select" }, { "style", "width:200px;" } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM