asp.net core 根据用户输入的文本,将搜索到的对应数据库信息显示出来(没有则给出提示),视图和控制器完整代码
时间: 2024-05-03 10:18:45 浏览: 8
以下是一个简单的示例,演示如何根据用户输入的文本在数据库中搜索并显示结果。
首先,在控制器中定义一个 `Search` 动作,该动作将接收用户输入的文本,并使用 Entity Framework Core 进行数据库查询。
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using YourProjectName.Models;
namespace YourProjectName.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Search(string query)
{
// 使用 EF Core 查询数据库
var result = await _context.Products
.Where(p => p.Name.Contains(query))
.ToListAsync();
// 将结果传递给视图
return View(result);
}
}
}
```
然后,创建一个名为 `Search.cshtml` 的视图,用于显示搜索结果。
```html
@model List<Product>
<form method="post" action="@Url.Action("Search")">
<input type="text" name="query" />
<button type="submit">搜索</button>
</form>
@if (Model.Any())
{
<h2>搜索结果</h2>
<ul>
@foreach (var product in Model)
{
<li>@product.Name</li>
}
</ul>
}
else if (!string.IsNullOrEmpty(Request.Form["query"]))
{
<p>没有找到匹配的结果。</p>
}
```
最后,确保在 `Startup.cs` 中正确配置应用程序的数据库连接和 Entity Framework Core。
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using YourProjectName.Models;
namespace YourProjectName
{
public class Startup
{
private IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
```
这是一个简单的示例,用于演示如何根据用户输入的文本在 ASP.NET Core 中搜索数据库并显示结果。请注意,此示例仅涵盖最基本的功能,并且可能需要根据您的实际需求进行修改。