简体   繁体   中英

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

I am using Razor Pages (not MVC) and keep getting the above error on the return statement. There is a similar question out there relating to the MVC model but the answer to that one is to change the class to "Controller". When I try that, page related things break. Any suggestions?

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);
    }

You're tried to use Json() method which derived from either System.Web.Mvc.JsonResult or System.Web.Http.ApiController.JsonResult instead of Microsoft.AspNetCore.Mvc.JsonResult namespace, they're all different namespaces. You should use the constructor of Microsoft.AspNetCore.Mvc.JsonResult to create JSON string instead:

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);
}

Reference: Working With JSON in Razor Pages

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM