如何解决 Razor Pages 错误 "CS0103 The name 'Json' does not exist in the current context"?

How do I solve the Razor Pages error "CS0103 The name 'Json' does not exist in the current context"?

我正在使用 Razor Pages(不是 MVC)并在 return 语句中不断收到上述错误。那里有一个与 MVC 模型相关的类似问题,但该问题的答案是将 class 更改为 "Controller"。当我尝试这样做时,与页面相关的内容会中断。有什么建议吗?

public class VehicleInfoPageModel : PageModel
{        
    public SelectList ModelNameSL { get; set; }

public JsonResult PopulateModelDropDownList(StockBook.Models.StockBookContext _context,
        int selectedMakeID,
        object selectedModelID = null)
    {
        var ModelIDsQuery = from m in _context.VehicleModel
                            orderby m.ModelID // Sort by ID.
                            where m.MakeID == selectedMakeID
                            select m;

        ModelNameSL = new SelectList(ModelIDsQuery.AsNoTracking(),
                    "ModelID", "ModelName", selectedModelID);
        return Json(ModelNameSL);
    }

您尝试使用派生自 System.Web.Mvc.JsonResult or System.Web.Http.ApiController.JsonResult instead of Microsoft.AspNetCore.Mvc.JsonResult 命名空间的 Json() 方法,它们都是不同的命名空间。您应该使用 Microsoft.AspNetCore.Mvc.JsonResult 的构造函数来创建 JSON 字符串:

public JsonResult PopulateModelDropDownList(StockBook.Models.StockBookContext _context, int selectedMakeID, object selectedModelID = null)
{
    var ModelIDsQuery = from m in _context.VehicleModel
                        orderby m.ModelID // Sort by ID.
                        where m.MakeID == selectedMakeID
                        select m;

    ModelNameSL = new SelectList(ModelIDsQuery.AsNoTracking(),
                "ModelID", "ModelName", selectedModelID);

    // return JSON string
    return new JsonResult(ModelNameSL);
}

参考:Working With JSON in Razor Pages