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.
$('#txtPrice').val(price.value)- but why are you returning 2 properties (labelandvalue) with the same value? You can also delete thecontentType:optionsuccess: function (price) { console.dir(price);and have a look at what propertiespricehas.