Jquery – dynamically fill fields with json based on property name

asp.netasp.net-mvcjqueryjson

  1. asp.net mvc model object is being fetched by ajax call – $.ajax(….
  2. form has fields with IDs exactly to matching properties on returned json object (created by Html.TextBox("NAME", Model.Order.NAME) )

How to automatically populate fields(inputs) with corresponding json object properties ?
Manually would be like $("#NAME).val(json.NAME) so how to make this dynamic?
Is there some kind of reflections (like System.Reflection in c#) for javascript/jquery ?

Best Answer

Maybe something like this:

$("#formId input").each(function(){
   $(this).val(json[$(this).attr("id")]);
});

... which iterates over all the form inputs, and looks for a JSON entry with the inputs ID.

The thing to note here is that you can retrieve json.NAME via json["NAME"].