MVC3 DropdownListFor not binding the model property to selected value Here is my View
@{var items = new List<SelectListItem>(){
new SelectListItem {Text = "2", Value = "2", Selected = true},
new SelectListItem {Text = "3", Value = "3", Selected = false},
new SelectListItem {Text = "4", Value = "4", Selected = false},
new SelectListItem {Text = "5", Value = "5", Selected = false}
};
}
@Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text"))
InvoiceModel has a property called InvoiceItem class which further has property Count of int type. The count property is always 0 and is not being updated to the value selected from dropdown.
Please help I have already spent hours on this. Thank You.
Thank You for the responses. But I still have the issue.
I used @Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "value", "text", 2))
also tried @Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "value", "text", "2"))
Count property is always 0. What am i missing here.
Use:
new SelectList(items, "value", "text", selectedvalue);
Ex:
@{var items = new List<SelectListItem>(){
new SelectListItem {Text = "2", Value = "2"},
new SelectListItem {Text = "3", Value = "3"},
new SelectListItem {Text = "4", Value = "4"},
new SelectListItem {Text = "5", Value = "5"}
};
}
@Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text", 2))
Maybe your problem is the same as mine. Please check whether x.InvoiceItem.Count is a property or a field. If it is a field, post data won't bind to it.
My model
public class SearchReportObject
{
public string report_type;
}
In cshtml
@Html.DropDownListFor(model => model.report_type, new SelectList( new List<Object>{new { value = "0" , text = "Red" },new { value = "1" , text = "Blue" },new { value = "2" , text = "Green"}} , "value", "text"))
On post form, report_type always has a value of null. But when I change report_type from a field to a property like this:
public class SearchReportObject
{
public string report_type{ set; get; }
}
It works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With