C#如何从Web服务将图像动态显示到GridView中

时间:2019-01-27 10:59:49

标签: c# asp.net web-services

下面有这段代码,这是我调用REST Web服务来填充我的gridview的代码。我当前要完成的事情是使用从api获取的image URL将图像显示在我的gridview上,而不仅仅是链接。有没有简单的方法可以做到这一点?任何帮助将不胜感激,谢谢!

public partial class Book : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public class Result
    {
        public string title { get; set; }
        public string subtitle { get; set; }
        public string price { get; set; }
        public string image { get; set; }
        public string url { get; set; }
    }

    public class SearchList
    {
        public int resultCount;
        public Result[] books;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string searchTerm = TextBox1.Text;
        var webRequest = (HttpWebRequest)WebRequest.Create
        ("https://api.itbook.store/1.0/search/" + Server.UrlEncode(searchTerm));
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string resString = sr.ReadToEnd();
            SearchList list = json.Deserialize<SearchList>(resString);
            GridView1.DataSource = list.books;
            GridView1.DataBind();
        }
        else
            Label1.Text = "Invalid Response";
    }
}

1 个答案:

答案 0 :(得分:0)

因为您要将“类”列表绑定到GridView。我建议使用带有ItemTemplate的Stronly Typed GridView。您必须确保ItemType属性指向您的课程。

<asp:GridView ID="GridView1" runat="server" ItemType="YourNameSpace.Result">
    <Columns>
        <asp:TemplateField HeaderText="Title">
            <ItemTemplate>

                <%# Item.title  %>

            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>

                <img src="<%# Item.url  %>" />

                <asp:Image ID="Image1" runat="server" ImageUrl='<%# Item.url %>' />

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>