Jooooosh
Jooooosh

Reputation: 331

DropDownListFor default selected item from model

I have a DropDownListFor bound to a model member as well as a list of items to choose from. The binding to this member works, but what I can't seem to figure out is how to display the current value of the model when the page loads.

View

@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.statuses)

Control

List<SelectListItem> statuses = new List<SelectListItem>();
statuses.Add(new SelectListItem { Text = "Approved", Value = "Approved" });
statuses.Add(new SelectListItem { Text = "Declined", Value = "Declined" });
statuses.Add(new SelectListItem { Text = "Pending", Value = "Pending" });
ViewBag.ClaimStatus = statuses;

Adding the optionLabel argument doesn't work and returns a null value, and passing in a SelectListItem as the optionLabel parameter doesn't work either.

@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.methodofpayment, model.MethodOfPayment)

I want the page to submit the same value shown if they don't change the list item.

Edit:
Thanks you guys it must have been a name conflict. I messed up asking my question a bit cause I have two drop down lists and I must have copied the wrong one.

The Changed Code:
Controller:

List<SelectListItem> statuses = new List<SelectListItem>();
statuses.Add(new SelectListItem { Text = "Approved", Value = "Approved" });
statuses.Add(new SelectListItem { Text = "Declined", Value = "Declined" });
statuses.Add(new SelectListItem { Text = "Pending", Value = "Pending" });
ViewBag.ClaimStatuses = statuses;

View:

@Html.DropDownListFor(model => model.ClaimStatus, (List<SelectListItem>)ViewBag.ClaimStatuses)

Made it plural and it works.

Upvotes: 3

Views: 869

Answers (2)

Bilel Chaouadi
Bilel Chaouadi

Reputation: 933

Be sure that you have just one control which has the name "model.MethodofPayment ".

@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.methodofpayment)

in the your post method use the name within your view

  [HttpPost]
     public ActionResult yourAction(classname ClassModel)
    {
    }

be sure that the name "ClassModel" is the same in the view

Upvotes: 0

Dennis R
Dennis R

Reputation: 3237

Sometimes it may happen that you might have used the same name for different controls/variables and it might conflict with each other.

In you case the Model property name MethodofPayment and your ViewBag name methodofpayment results in conflict I guess.

Try changing your ViewBag name to something like ViewBag.paymentmode and try it.

@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.paymentmode)

Upvotes: 3

Related Questions