如何将Localhost的ASP.NET Web Forms网站GridView接入UWP应用?
Hey there! Let's break down what's going on with your code and fix this step by step—no jargon overload, promise!
The Problem With Your Current Code
Right now, when you use HttpClient to call AdvGridView.aspx, you're getting the full HTML source code of the web page, not just the data inside the GridView. That's why you can't directly use it in your UWP app's GridView—you're trying to bind raw HTML instead of structured data like JSON.
The Fix: Two Key Steps
We need to first create a way for your ASP.NET Web Forms site to return clean, usable data (not HTML), then modify your UWP code to fetch and display that data.
Step 1: Add a Data Endpoint to Your ASP.NET Web Forms Site
Instead of requesting the full page, we'll make a simple "API" that returns your GridView data as JSON (a lightweight, easy-to-read data format). Here's how:
- In your Web Forms project, add a Generic Handler (right-click project → Add → New Item → Generic Handler, name it
GetAdData.ashx). - Replace its code with this (adjust the data-fetching logic to match your actual GridView data source):
using System; using System.Web; using System.Web.Script.Serialization; using System.Data; public class GetAdData : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; // Replace this with YOUR logic to get the GridView's data (e.g., from a database) DataTable adData = GetAdDataFromSource(); // Convert the data to JSON JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonOutput = serializer.Serialize(adData); context.Response.Write(jsonOutput); } // Simulated data source—replace this with your actual data retrieval code private DataTable GetAdDataFromSource() { DataTable dt = new DataTable(); // Add columns that match your GridView's fields dt.Columns.Add("AdId", typeof(int)); dt.Columns.Add("AdTitle", typeof(string)); dt.Columns.Add("AdDescription", typeof(string)); // Add sample rows (you'll pull these from your database instead) dt.Rows.Add(1, "Summer Sale", "50% off all outdoor gear"); dt.Rows.Add(2, "New Arrivals", "Check out our latest tech products"); return dt; } public bool IsReusable => false; }
Test this endpoint by opening http://localhost:7665/GetAdData.ashx in your browser—you should see clean JSON text with your data.
Step 2: Update Your UWP App to Fetch and Display the JSON Data
First, create a model class to match your data structure (right-click your UWP project's Models folder → Add → Class, name it AdItem.cs):
namespace TMD_Display.Models { public class AdItem { public int AdId { get; set; } public string AdTitle { get; set; } public string AdDescription { get; set; } // Add any other fields from your GridView here } }
Next, update your Ad.xaml to add a data template for your GridView (so it knows how to display each AdItem):
<Page x:Class="TMD_Display.Views.Ad" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TMD_Display.Views" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:models="using:TMD_Display.Models" mc:Ignorable="d" Loaded="Page_Loaded" Height="600"> <Grid Name="myGrid"> <GridView x:Name="adGridView" ItemsSource="{x:Bind AdItems}"> <GridView.ItemTemplate> <DataTemplate x:DataType="models:AdItem"> <StackPanel Margin="15" Width="200"> <TextBlock Text="{x:Bind AdTitle}" FontSize="18" FontWeight="Bold"/> <TextBlock Text="{x:Bind AdDescription}" FontSize="14" Foreground="DarkGray" Margin="0,5,0,0"/> <TextBlock Text="ID: {x:Bind AdId}" FontSize="12" Margin="0,5,0,0"/> </StackPanel> </DataTemplate> </GridView.ItemTemplate> </GridView> </Grid> </Page>
Finally, update your Ad.xaml.cs to fetch the JSON, parse it, and bind it to the GridView:
using System.Collections.ObjectModel; using System.Collections.Generic; using Windows.Web.Http; using Newtonsoft.Json; // Install this via NuGet (right-click project → Manage NuGet Packages → search "Newtonsoft.Json") namespace TMD_Display.Views { public sealed partial class Ad : Page { // ObservableCollection automatically updates the UI when data changes public ObservableCollection<Models.AdItem> AdItems { get; set; } = new ObservableCollection<Models.AdItem>(); public Ad() { this.InitializeComponent(); } private void Page_Loaded(object sender, RoutedEventArgs e) { _ = LoadAdData(); // Ignore async warning safely here } private async Task LoadAdData() { try { using (HttpClient httpClient = new HttpClient()) { // Set a user-agent header (some servers require this) httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); // Call our new data endpoint Uri requestUri = new Uri("http://localhost:7665/GetAdData.ashx"); HttpResponseMessage response = await httpClient.GetAsync(requestUri); response.EnsureSuccessStatusCode(); // Throws an error if the request fails // Read and parse the JSON data string jsonData = await response.Content.ReadAsStringAsync(); List<Models.AdItem> adList = JsonConvert.DeserializeObject<List<Models.AdItem>>(jsonData); // Update the UI with the new data AdItems.Clear(); foreach (var ad in adList) { AdItems.Add(ad); } } } catch (Exception ex) { // Add error handling here (e.g., show a message to the user) // Example: // var errorDialog = new ContentDialog // { // Title = "Oops!", // Content = $"Failed to load ads: {ex.Message}", // PrimaryButtonText = "OK" // }; // await errorDialog.ShowAsync(); } } } }
Quick Tips for Beginners
- Test the endpoint first: Always make sure
GetAdData.ashxreturns valid JSON in your browser before trying to use it in UWP. - NuGet Package: Don't forget to install Newtonsoft.Json for JSON parsing (or use .NET's built-in
System.Text.Jsonif you prefer). - Network Access: If you're testing on a real device, ensure your UWP app has internet access (check Package.appxmanifest → Capabilities → Internet (Client)).
内容的提问来源于stack exchange,提问作者Alisa Fathima

