This is the error I’m getting. The data is being retrieved through WebAPI, but due to a gridview setting, it is not displaying the retrieved data.
protected void Page_Load(object sender, EventArgs e)
{
try
{
var webRequest = (HttpWebRequest)WebRequest.Create("https://localhost:44342/api/author");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
//Console.WriteLine(arr);
GridView1.DataSource = arr;
GridView1.DataBind();
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
webform.aspx file gridview code
<asp:GridView ID="GridView1" Class="mygridview" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" BorderStyle="Solid" CellPadding="10" >
<Columns>
<asp:BoundField DataField="author_id" HeaderText="AuthorID" />
<asp:BoundField DataField="author_name" HeaderText="firstName" />
</Columns>
</asp:GridView>
Controller code:
public IHttpActionResult getauthor()
{
librariaEntities lb = new librariaEntities();
var results = lb.Authors.ToList();
return Ok(results);
}
2
Answers
Deseriaziled the returned value from the web API as a list (or array) of Author objects and it worked eventually.
Okay, this looks pretty simple.
The
GridView
control needs to bind to a list of objects. You’re doing this with theJArray
. So far, so good.But the
GridView
doesn’t know how to get properties called "author_id" and "author_name" from the objects in theJArray
. There are no such strongly-typed properties in those objects.Can you deserialize your return value from the web API as a list (or array) of
Author
objects?Incidentally, you’re working with ASP.Net WebForms, not MVC.