3

This is the sample of the model class

[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public int SelectedValue { get; set; }


[Required(ErrorMessage = "Department is required")]
[Display(Name = "Department")]
public List<Department> RoleList { get; set; }

This is the view

<div class="col-md-10">
    @Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })
    @Html.ValidationMessageFor(model => model.SelectedValue, "",new { @class = "text-danger"})
</div>

The list is populated perfectly from the database. Now when i select the item on the list, the select value has to be sent to the controller

public async Task<ActionResult> Register(RegisterViewModel model)
{
    int Selectedvalue = model.SelectedValue;
    if (ModelState.IsValid && (model.SelectedValue).ToString() != "0")
    {

Here i have made a selection

enter image description here

Error

enter image description here

2
  • 1
    We can't see your error. Commented Dec 6, 2017 at 16:48
  • @MattSpinks , it has been solved Commented Dec 6, 2017 at 17:28

1 Answer 1

3

You should change it

@Html.DropDownListFor(m => m.RoleList, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

To

@Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.RoleList,"ID", "RoleName","1"), "Please Choose a Department", new { htmlAttributes = new { @class = "form-control"} })

The first parameter of the DropDownListFor should be selected value in model. In your case, this property is Model.SelectedValue not Model.RoleList.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition you can remove the Required attribute from RoleList becuase it is not POST'ed to the server and the Display attribute because are displaying that property, you are displaying the property of SelectedValue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.