You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#实现ASP.NET中HTML按钮与数据库的连接?

Hey there! Since you're new to C# and .NET, let's walk through adding database-connected search functionality to that button—we'll cover both front-end adjustments and back-end code that actually talks to your database.

Step 1: Tweak the Front-End Form

First, your current code is just a div with an input and button. To make it work with ASP.NET, wrap it in a <form> tag so the submit action triggers a back-end method. We'll use ASP.NET MVC tag helpers here (they make life easier):

<form asp-controller="Search" asp-action="Index" method="get">
  <div class="input-group">
    <input type="text" name="q" class="form-control" placeholder="Search..." />
    <span class="input-group-btn">
      <button type='submit' name='search' id='search-btn' class="btn btn-flat">
        <i class="fa fa-search"></i>
      </button>
    </span>
  </div>
</form>

The asp-controller and asp-action attributes tell ASP.NET which controller/method to call when the button is clicked.

Step 2: Create the Back-End Controller Action

Next, let's make a SearchController with an Index method that handles the search query. I'll show two common approaches: ADO.NET (straightforward for beginners) and EF Core (modern, ORM-based).

Option 1: Using ADO.NET (Direct Database Calls)

First, add your database connection string to appsettings.json:

"ConnectionStrings": {
  "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=YOUR_DB_NAME;Trusted_Connection=True;TrustServerCertificate=True;"
}

Then create the controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;

public class SearchController : Controller
{
    private readonly IConfiguration _config;

    // Inject configuration to access the connection string
    public SearchController(IConfiguration config)
    {
        _config = config;
    }

    // This method runs when the form is submitted
    public IActionResult Index(string q)
    {
        var results = new List<string>(); // Replace with your actual model type

        if (!string.IsNullOrEmpty(q))
        {
            // Connect to the database
            using (var connection = new SqlConnection(_config.GetConnectionString("DefaultConnection")))
            {
                connection.Open();
                // Write your search query (adjust table/column names to match your DB)
                var query = "SELECT Name FROM Products WHERE Name LIKE @SearchTerm";
                
                using (var command = new SqlCommand(query, connection))
                {
                    // Use parameterized query to prevent SQL injection!
                    command.Parameters.AddWithValue("@SearchTerm", $"%{q}%");
                    
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            results.Add(reader.GetString(0)); // Add results to your list
                        }
                    }
                }
            }
        }

        // Pass results to the view to display
        return View(results);
    }
}

Option 2: Using EF Core (ORM Approach)

If you're using Entity Framework Core (recommended for most projects), first set up your DbContext:

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    // Replace with your actual DB set
    public DbSet<Product> Products { get; set; }
}

// Your Product model (matches your DB table)
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then update the controller method:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public class SearchController : Controller
{
    private readonly AppDbContext _context;

    public SearchController(AppDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index(string q)
    {
        var results = new List<Product>();

        if (!string.IsNullOrEmpty(q))
        {
            // EF Core query with parameterization (safe from SQL injection)
            results = await _context.Products
                .Where(p => p.Name.Contains(q))
                .ToListAsync();
        }

        return View(results);
    }
}
Step 3: Display Results in the View

Finally, create a Views/Search/Index.cshtml view to show the search results:

@model List<Product> <!-- Or List<string> if using ADO.NET -->

<!-- Your search form goes here (copy the form from Step 1) -->

@if (Model.Any())
{
    <h3>Search Results</h3>
    <ul>
        @foreach (var item in Model)
        {
            <li>@item.Name</li> <!-- Adjust based on your model -->
        }
    </ul>
}
else if (!string.IsNullOrEmpty(Request.Query["q"]))
{
    <p>No results found for "@Request.Query["q"]".</p>
}

Quick Notes for Beginners:

  • Make sure to install required NuGet packages:
    • For ADO.NET: Microsoft.Data.SqlClient
    • For EF Core: Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools
  • Always use parameterized queries (like we did) to avoid SQL injection attacks—never concatenate user input directly into SQL!
  • Test your connection string first to ensure it can reach your database.

内容的提问来源于stack exchange,提问作者EmmyAyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:58:34