Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdownlist for not binding to model property mvc3

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.

like image 970
user2548196 Avatar asked Dec 03 '25 23:12

user2548196


2 Answers

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))
like image 63
Cyberdrew Avatar answered Dec 07 '25 21:12

Cyberdrew


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.

like image 40
Bùi Đức Khánh Avatar answered Dec 07 '25 22:12

Bùi Đức Khánh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!