Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet) ISSUE

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet); method is changed and not allowing to set JsonrequestBehavior. What is alternative in MVC6

like image 370
Rahul Sharma Avatar asked Jan 06 '23 08:01

Rahul Sharma


2 Answers

That overload of Json method which takes JsonRequestBehavior does not exist in the aspnet core any more.

You can simply call the Json method with the object data you want to send back.

public IActionResult GetJsonData()
{
  var rows = new List<string>  {  "Item 1","Item 2" };
  return Json(rows);
}

Or even

public IList<string> GetJsonData()
{
    var rows = new List<string>  {"aa", "bb" };
    return rows;
}

or using Ok method and having IActionResult as the return type.

public IActionResult GetJsonData()
{
   var rows = new List<string>   { "aa",  "bb"  };
    return Ok(rows);
}

and let the content negotiator return the data in the requested format(via Accept header). The default format used by ASP.NET Core MVC is JSON. So if you are not explicitly requesting another format(ex :application/xml), you will get json response.

like image 105
Shyju Avatar answered Apr 26 '23 13:04

Shyju


Try this

 [HttpGet]
    public JsonResult List()
    {          
        var settings = new JsonSerializerSettings();

        return Json(rows, settings);
    }
like image 32
Moro Avatar answered Apr 26 '23 15:04

Moro