这是我的问题:我有一个有两个选择元素(下拉)的页面。第一个选项选择一个值,当第一个选项更改时,我希望第二个下拉列表加载值。
我已经知道可以使用asp-items属性将值“绑定”到下拉列表中。
我试图在第一个select元素上使用onchange方法,然后在JS中调用模型中的一个方法来加载项目。
但我发现了一个错误:
不能隐式地将类型'void‘转换为'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();
}我做错了什么?
发布于 2022-04-25 08:21:08
在.cshtml页面脚本部分,不能直接使用@Model.UpdateVariants();调用处理程序方法。对于UpdateVariants处理程序方法,需要返回JsonResult,而不是使用void。
要在Razor页面中使用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>
}结果如下:

更详细的信息,请参阅Razor页面中AJAX的级联下拉列表。
https://stackoverflow.com/questions/71991517
复制相似问题