mvc list to jsonresult 1

mvc list to jsonresult

public JsonResult GetAreasForCompany(int companyId)
  var areas = context.Areas
    .Where(x => x.Company.CompanyId == companyId)
    .Select(a => new
      AreaId = a.AreaId,
      Title = a.Title
  return Json(areas);

Here is what the above code is Doing:
1. The GetAreasForCompany method is decorated with the HttpPost attribute. This means that the method will only be called when the client makes a POST request to the server.
2. The method takes a single parameter, companyId. This parameter will be populated with the value of the companyId property of the object that is sent to the server.
3. The method returns a JsonResult. This is a special type of ActionResult that is used to return JSON data to the client.
4. The method uses LINQ to Entities to query the Areas table in the database. The query returns all of the areas that belong to the company with the specified companyId.
5. The query returns an anonymous type that contains the AreaId and Title properties of each area.
6. The query results are returned to the client as JSON data.

Here’s the JavaScript code that calls the GetAreasForCompany method:

Similar Posts