F. Flores F. Flores - 5 months ago 11
jQuery Question

How to add value to input with ajax

my table have a field Id which is identity, autoincrement and zerofill, starts with 000001. Thats ok, Im using ajax and c# web service, my query is this:

sql = "Select Id FROM table WHERE (Owner ='" + us + "')";


This is my WebMethod

public string IdRegis(string us)
{
string resp = "";
DataTable dt = conn.ConsultTable("id", us);(This is query at top)

Opc2 op;
List<Opc2> lista = new List<Opc2>();
for (int i = 0; i < dt.Rows.Count; i++)
{
op = new Opc2((string)dt.Rows[i]["Id"].ToString());
lista.Add(op);
op = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
resp = js.Serialize(lista);
return resp;
}


And this is mi class

public class Opc2
{
public Opc2() { }

public Opc2(string item)
{
Item = item;
}

public string Item { get; set; }
}


And ajax success function:

success: function (data) {
var options = '<option disabled="disabled" selected="selected">Select an option...</option>';
var datas = JSON.parse(data.d);

for (var i = 0; i < datas.length; i++) {
var id = ("00000" + (parseInt(datas[i].Id)));
var zerofillid = id.substring(id.length - 5);

options += '<option value ="' + zerofillid + '">';
options += zerofillid;
options += '</option>';
}
$('#id').html(options);
}


My select gets this values 00NaN.

Answer

Your for loop in Javascript. Change it like this.

for (var i = 0; i < datas.length; i++) 
{
    // changed id to Item in this line
    var id = ("00000" + (parseInt(datas[i].Item)));

    var zerofillid = id.substring(id.length - 5);

    optiones += '<option value ="' + zerofillid + '">';
    options += zerofillid;
    options += '</option>';
}