C# ASP.NET 核心 Razor 页面 - 从 Razor 页面内部调用 PageModel 方法?

C# ASP.NET Core Razor page - call PageModel method from inside the Razor page?

这是我的问题:我的页面有 2 个 Select 元素(下拉菜单)。第一个 select 是一个值,当第一个 selection 更改时,我希望第二个下拉列表加载值。

我已经知道我可以使用 asp-items 属性 将值“绑定”到下拉列表中。

我正在尝试在第一个 select 元素上使用 onchange 方法,然后在 JS 脚本中调用模型中的方法来加载项目。

但是我得到一个错误:

Cannot implicitly convert type 'void' to 'object'

这是我的 html.cs:

<a>Article: </a>
<select name="Articles" id="articles" asp-for="@Model.SelectedArticleTag" asp-items="@Model.ArticlesDropdownItems">
    <option value="notChosen">Choose Article...</option>
</select>

<br/>

<a>Article Variant: </a>
<select name="ArticleVariants" id="variants" asp-items="@Model.ArticleVariantsDropdownItems">
    <option value="notChosen">Choose Variant...</option>
</select>

这是我的 html.cs 脚本部分,用于获取 onchange 事件:(@Model.UpdateVariants(); 显示我在顶部提到的错误)

@section scripts {
<script>
    $("#articles").on("change", function () {

        @Model.UpdateVariants();
    });
</script>
}

这是我要调用的 PageModel 方法(未调用):

public void UpdateVariants()
{
     string articleNumber = ArticlesDropdownItems[SelectedArticleTag].Value;

     var unifiedVariants = LoadVariants(articleNumber).Result.ToList();

     ArticleVariantsDropdownItems = unifiedVariants.Select(v => new SelectListItem
        {
            Value = v.ArticleVariantNumber,
            Text = $"{v.ArticleVariantNumber} - {v.ArticleVariantSize} - {v.ArticleVariantPrice}"
        }).ToList();
}

我做错了什么?

在.cshtml页面Script部分,不能直接使用@Model.UpdateVariants();调用handler方法。对于 UpdateVariants 处理程序方法,您需要 return JsonResult,而不是使用 void.

要在 Razor Pages 中使用 AJAX 创建级联下拉列表,您可以参考以下代码:

.cshtml.cs 文件中的代码:

public class CascadingDropdownsModel : PageModel
{
    private ICategoryService categoryService;
    public CascadingDropdownsModel(ICategoryService categoryService) => this.categoryService = categoryService;
    [BindProperty(SupportsGet = true)]
    public int CategoryId { get; set; }
    public int SubCategoryId { get; set; }
    public SelectList Categories { get; set; }

    public void OnGet()
    {
        //get the category data, and popuplate the first dropdown list.
        Categories = new SelectList(categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));
    }
    public JsonResult OnGetSubCategories()
    {
        //based on the categoryid to find all subcategories, then return them to the view page and populate the second dropdownlist.
        return new JsonResult(categoryService.GetSubCategories(CategoryId));
    }
}

.csthml 文件中的代码:

@page
@model RazorAPP.Pages.CascadingDropdownsModel
<h4>Categories</h4>
<select asp-for="CategoryId" asp-items="Model.Categories">
    <option value="">Select Category</option>
</select>
<h4>SubCategories</h4>
<select asp-for="SubCategoryId"></select>

@section scripts{ 
<script>
    $(function () {
        $("#CategoryId").on("change", function() {
            var categoryId = $(this).val();
            $("#SubCategoryId").empty();
            $("#SubCategoryId").append("<option value=''>Select SubCategory</option>");
            $.getJSON(`?handler=SubCategories&categoryId=${categoryId}`, (data) => {
                $.each(data, function (i, item) {
                    $("#SubCategoryId").append(`<option value="${item.subCategoryId}">${item.subCategoryName}</option>`);
                });
            });
        });
    });
</script>
}

结果是这样的:

更多详细信息,请参阅Cascading Dropdowns With AJAX in Razor Pages