jquery - DropDownList value and text -


i using jquery populate dropdown list in asp.net mvc

$(function () {     $.getjson('/getfoo', function (result) {         var ddl = $('#foo');         ddl.empty();         $(result).each(function () {             $(document.createelement('option'))                 .attr('value', this.id)                 .text(this.text)                 .appendto(ddl);         });     }); }); 

here's controller action return json used in process:

public actionresult getfoo() {     viewbag.idtable = new selectlist(db.table, "idtable", "description");         return json(viewbag.idtable, jsonrequestbehavior.allowget); } 

and here's how dropdown list goes view:

@html.dropdownlistfor(model => model.idtable,enumerable.empty<selectlistitem>(), "-- loading values --", new { id = "foo" }) 

to clarify more i'm doing, want show description in select list options instead of idtable.

everything works fine until moment validate dropdown list choice. in fact, gives following error:

the value [choice] not valid idtable.

so guess values of select list options set description field, rather id field.

how can fix that?

try this:

public actionresult getfoo() {     return json(db.table.select(x=> new { id = x.idtable, text = x.description}),          jsonrequestbehavior.allowget); } 

or in js change

.attr('value', this.id) 

to

.attr('value', this.value) 

Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -