jquery - Asp.Net MVC 5 Fill EditorFor When Dropdown SelectedItem Changed -


i need fill html.editorfor controls when select product dropdown. newbie @ jquery , ajax.

my dropdown:

@html.dropdownlist("productid", null, htmlattributes: new { @class = "form-control",  @onchange= "fillprice()", id= "productid" }) 

editorfor:

@html.editorfor(model => model.productprice,                  new { htmlattributes = new {                             @class = "form-control",                              id="txtprice" } }) 

javascript:

function fillprice() {     var productid = $('#productid').val();     $.ajax({         url: '@url.action("getprice")',         datatype: "json",         data: { productid: productid },         contenttype: "application/json; charset=utf-8",         success: function (price) {             $('#txtprice').val()   ??? write here fill txtprice?         }     });     } 

controller/getprice:

public jsonresult getprice(int productid) {     var price = r in db.products                 r.id == productid                 select new {                       id = r.id,                       label = r.productprice,                       value = r.productprice };     return json(price, jsonrequestbehavior.allowget); } 

up point, works. check firebug , see json , results can't bind value editorfor.

the response in javascript in price variable:

function (price) {     //... } 

based on server-side code, looks object has 3 values:

new {      id = r.id,      label = r.productprice,      value = r.productprice } 

(i'm not sure why need same value twice, whatever.)

so you're looking value property of variable?:

$('#txtprice').val(price.value); 

you can check browser's debugger , see structure of price variable make sure.


edit: looks return value may array. makes sense given server-side code resulting in ienumerable<>. if should returning single value, might make explicit. this:

return json(price.single(), jsonrequestbehavior.allowget); 

you'll want add error checking around that, , logic handling errors (multiple found values or no found value) you.

conversely, if want array, access array client-side:

$('#txtprice').val(price[0].value); 

again, you'd want add error checking (in client-side code time) make sure value exists before trying use it.


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -