1

I need to fill Html.EditorFor controls when I select an product from Dropdown. I am very newbie at JQuery and 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()   ??? What to write here to fill txtPrice?
        }
    });  
  }

Controller/GetPrice:

public JsonResult GetPrice(int ProductId)
{
    var price = from r in db.Products
                where r.Id == ProductId
                select new { 
                     id = r.Id, 
                     label = r.ProductPrice, 
                     value = r.ProductPrice };
    return Json(price, JsonRequestBehavior.AllowGet);
}

Up to this point, everything works. I check with Firebug and see the Json get and results but I can't bind the value to the EditorFor.

3
  • $('#txtPrice').val(price.value) - but why are you returning 2 properties (label and value) with the same value? You can also delete the contentType: option Commented Sep 30, 2015 at 11:55
  • Add: success: function (price) { console.dir(price); and have a look at what properties price has. Commented Sep 30, 2015 at 11:59
  • I deleted contentType block and also label= r.ProductPrice properties. Then I tried '$('#txtPrice').val(price.value)' but doesn't work. Commented Sep 30, 2015 at 12:02

1 Answer 1

1

The response in your JavaScript is in the price variable:

function (price) {
    //...
}

Based on the server-side code, it looks like that object has three values:

new { 
    id = r.Id, 
    label = r.ProductPrice, 
    value = r.ProductPrice }

(I'm not sure why you need the same value twice, but whatever.)

So you're probably looking for the value property of that variable?:

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

You can also check your browser's debugger and see the structure of the price variable to make sure.


Edit: It looks like the return value may be an array. Which makes sense given that the server-side code is resulting in an IEnumerable<>. If it should only be returning a single value, you might make that explicit. Something like this:

return Json(price.Single(), JsonRequestBehavior.AllowGet);

You'll want to add some error checking around that, and the logic for handling errors (multiple found values or no found value) is up to you.

Conversely, if you want it to be an array, you would access it as an array client-side:

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

Again, you'd want to add some error checking (in the client-side code this time) to make sure a value exists before trying to use it.

Sign up to request clarification or add additional context in comments.

8 Comments

With Google Chrome Debugger, on Network tab I see that result: [{id: 14, value: 24}]. But $('#txtPrice').val(price.value); doesn't give me the value: 24
@degergio: According to that debugger output, it looks like price is an array. Try: price[0].value instead. Though you may want to change the server-side code to return a single value if you're only expecting a single value.
Oh, thank you. That worked for me. $('#txtPrice').val(price[0].value); gave me the result. If you edit your answer, I will mark as answer to help others.
@degergio: Answer is now updated with a couple of options. I recommend modifying the server-side code accordingly so that the API exposes what you expect it to. But it's up to you and how you want to structure your API (and where you want to encapsulate any error checking and defensive programming).
When defining the Product, Price is Required and Dropdown populate with only the existing Products. So there is no chance to be null or empty response if you select the product from this Dropdown.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.