简体   繁体   中英

how to bind json data in datalist using knockout js

here is my web services code:

 public class SympsService : System.Web.Services.WebService
{

    [WebMethod]
    public symps GetSymptoms(string organ_name)
    {
      symps Symptoms  = new symps();
        string CS = ConfigurationManager.ConnectionStrings["EhealtsCS"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("sendSymptoms", con);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter = new SqlParameter();
            parameter.ParameterName = "@organ";
            parameter.Value = organ_name;
            cmd.Parameters.Add(parameter);
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.Read())
            {
                Symptoms.Sympt = rdr["SymptomsName"].ToString();
            }
              return Symptoms;
        }    
    }
}

it returns json data to jquery ajax.this is my ajax code:

$.ajax({
                url: 'SympsService.asmx/GetSymptoms',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ organ_name: 'toes' }),
                method: 'post',
                dataType: 'json',
                success: function (data) {

                    $('#Text1').val(data.d.sympt);
                },
                error: function (err) {
                    alert(err);
                }
            });

now i show data in text box but i want to show it on datalist using knockout js or something like that which can show every data dynamically.how can i do that. any lead is also appreciate. is there any better way to do this? thanks in advance.

Actually, every front end framework solves this task. If you want to use knockout.js, you may write something like (not tested):

var DataGridModel = function() {
  this.rows = ko.observableArray();
}

var dataGrid = new DataGridModel();
ko.applyBindings(dataGrid);

$.ajax({
  ...
  success: function(data) {
    dataGrid([]);
    // Assume data is key-value store like {key1:'value1',key2:'value2'}
    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        dataGrid.push({key:key,value:data[key]});
      }
    }
  }
});

You also have to write html code like:

<table>
  <tbody data-bind="foreach:rows">
    <tr>
      <td data-bind="text:key"></td>
      <td data-bind="text:value"></td>
    </tr>
  </tbody>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM