在 asp.net core razor 页面的部分视图中使用表单

问题描述

我有以下结构:
SelectLoc.cshtml

@model SelectLocModel

<div class="dropdown">
    <form method="get">
        <select asp-for="Location" asp-items="Model.Locations"
                class="btn btn-secondary" formaction="Partials/SelectLoc" onchange="this.form.submit()">
        </select>
    </form>
</div>

SelectLoc.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;

namespace AdminPortal.Web.Pages.Partials
{
    public class SelectLocModel : PageModel
    {
        private readonly HttpClient httpClient;

        private readonly string key = "FAKE TOKEN";

        public string Location { get; set; }

        public List<SelectListItem> Locations { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = null,Text = "Select Location" },new SelectListItem { Value = "Kothrud",Text = "Kothrud" },new SelectListItem { Value = "Dhanakawdi",Text = "Dhanakawdi" },new SelectListItem { Value = "Karvenagar",Text = "Karvenagar" },new SelectListItem { Value = "Wakad",Text = "Wakad" },};

        public SelectLocModel(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public void OnSubmit()
        {

        }

        public void OnGet()
        {
            
        }

        public void OnGetSubmit()
        {

        }

        public async void OnGetLocation()
        {
            string geocodeRequest = $"https://maps.googleapis.com/maps/api/geocode/json?address={Location}&key={key}";
            Location jsonResponse = await httpClient.GetFromJsonAsync<Location>(geocodeRequest);
        }
    }
}

我知道,在任何方法中都没有任何有用的代码,但我希望表单在代码隐藏文件中使用 OnGet 处理程序。它以某种方式不断调用 ctor。我做错了什么?

解决方法

如果您想在提交表单时转到https://localhost:xxx/Partials/SelectLoc?Location=xxx,可以在表单中添加action="/Partials/SelectLoc"

SelectLoc.cshtml:

@model SelectLocModel
<div class="dropdown">
<form method="get" action="/Partials/SelectLoc">
    <select asp-for="Location" asp-items="Model.Locations"
            class="btn btn-secondary" formaction="Partials/SelectLoc" onchange="this.form.submit()">
    </select>
</form>
结果:

enter image description here