Reputation: 179
I'm retrieving data from edit_retrun.aspx page. Data successfully return, I check through alert(data.d);
format came look like this to ajax success called method
[{"id":"464","fname":"dsf","age":"34"}]
but when I tried to pass the data into relevant textboxes it won't display the result atext boxeses no errors were displayed. what I tried so far I attached below.
these are the textbox to pass the data.
$('#fname').val(data.fname);
$('#age').val(data.age);
Ajax full code
$.ajax({
type: 'POST',
url: 'edit_return.aspx/doSome',
dataType: 'JSON',
data: "{id: '" + id + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
console.log(data.fname);
$("html, body").animate({ scrollTop: 0 }, "slow");
isNew = false
$('#fname').attr('value', data.fname);
$('#fname').val(data.fname);
$('#age').val(data.age);
},
edit_retrun.aspx page
[WebMethod]
public List<Employee> doSome(int id)
{
SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
string sql = "select * from record where id='" + id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
List<Employee> employees = new List<Employee>();
employees = dt.AsEnumerable()
.Select(x => new Employee()
{
id = x.Field<int>("id").ToString(),
fname = x.Field<string>("name"),
age = x.Field<int>("age").ToString(),
}).ToList();
return employees;
}
Form Design
<form id="frmProject" runat="server">
<div>
<label class="form-label">First Name</label>
<input type="text" id="fname" name="fname" class="form-control" required />
</div>
<div class="form-group" align="left">
<label class="form-label">Age</label>
<input type="text" id="age" name="age" class="form-control" required />
</div>
<div>
<input type="button" id="b1" value="add" class="form-control" onclick="addProject()" />
</div>
</form>
Upvotes: 1
Views: 556
Reputation: 10707
As you said when you alert(data.d)
it gives:
[{"id":"464","fname":"dsf","age":"34"}]
Use this:
$('#fname').attr('value', data.d[0].fname);
Working Demo:
var d= [{"id":"464","fname":"dsf","age":"34"}]
$('#fname').attr('value', d[0].fname);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname">
Upvotes: 1