DropDownList For the default selected item from the model.

I have a DropDownListFor bound to a model member and also a list of items to choose from. Binding to this member works, but I can't figure out how to display the current value of the model on page load.

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 optionLabel argument does not work and returns null and passing in SelectListItem as optionLabel does not work either.

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

      

I want the page to display the same value as long as they don't change the list item.

Edit:
Thank you guys, this must be a name conflict. I got confused by asking my question because I have two dropdowns and I had to copy the wrong one.

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.

+3


source to share


2 answers


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

In your case, the property name Model MethodofPayment

and your ViewBag name MethodofPayment

leads to a conflict, I guess.



Try changing the name of the ViewBag to something like ViewBag.paymentmode

and try it.

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

      

+3


source


Make sure you only have one control named "model.MethodofPayment".

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

      

in post method use name in your view



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

      

make sure the name "ClassModel" is the same in the view

0


source







All Articles