【发布时间】:2021-01-19 09:24:14
【问题描述】:
我有以下部分位于Pages/Partials/
Search.cshtml:
@model SearchModel
<body>
<form method="get">
<div class="d-flex flex-row">
<div id="search-div" class="form-group">
<input asp-for="@Model.SearchString" value="@Model.SearchString" class="form-control" id="search-bar" placeholder="Enter ID" />
</div>
<div>
<button class="btn btn-primary" type="submit">Search</button>
</div>
</div>
</form>
</body>
Search.chshtml.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AdminPortal.Web.Pages.Partials
{
public class SearchModel : PageModel
{
[BindProperty(SupportsGet = true)]
public string SearchString { get; set; }
public void OnGet()
{
}
}
}
Home.cshtml.cs:
@page "/Home"
@using AdminPortal.Web.Pages
@model HomeModel
<body>
<partial name="Partials/Search" model="new Pages.Partials.SearchModel()" />
<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />
</body>
startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
namespace AdminPortal.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
但是,当我单击提交时,它不会调用OnGet() 方法。我做错了什么?
【问题讨论】:
-
手动添加表单动作:
action="/Partials/Search"可能是一个解决方案。但实际上如果您不指定动作,它在我的项目中也可以正常工作。我认为您需要找出导致无法正常工作的原因在您的项目中。请分享您的 Startup.cs。并请在首次渲染搜索页面时检查浏览器中的请求url是否为/Partials/Search。 -
嗨@d4rk4ng31,你可以看到你在首页添加了
Partials/Search作为部分,请求的url应该是/Home。当你提交表单时,它会转到/Home,这就是为什么您没有进入搜索 OnGet 方法的原因。在您的场景中,您必须指定表单操作:action="/Partials/Search"。 -
您介意分享您的主页后端代码吗?您的主页在哪里?在 Pages 文件夹或任何其他文件夹中?
-
@Rena。我在chat room
标签: c# asp.net-core get partials