0

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?

0

1 Answer 1

1

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;" } })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.