I need fill some dropdown combo so I create a WebApi and is working OK.
[HttpGet]
[Route("api/States/FindMunicipalityByStateID")]
public IHttpActionResult FindMunicipalityByStateID(String StateID)
{
List<MunicipalityModel> municipality = db.municipality.Where(p => p.StateID == StateID)
.Select(p => new MunicipalityModel
{
Name = p.Name,
MunicipalityID = p.MunicipalityID
})
.OrderBy(p => p.Name)
.ToList();
if (municipality == null)
{
return NotFound();
}
return Ok(municipality);
}
I read it using JQuery.getJSON
, and also works fine:
$('#StateID').change(function () {
var URL = 'http://myServer/myProject/api/States/FindMunicipalityByStateID?StateID=' + $('#StateID').val();
$.getJSON(URL, function (data) {
var items = '<option>Seleccione Municipio</option>';
$.each(data, function (i, municipality) {
items += "<option value='" + municipality.WeekID + "'>" + municipality.Name + "</option>";
});
$('#MunicipalityID').html(items);
});
});
The thing is now I want do the same but there is already an ASP.NET MVC controller from my EF wizard for that class so I try to do the same there.
I got 3 errors:
The type or namespace name 'IHttpActionResult' could not be found (are you missing a using directive or an assembly reference?)
The name 'NotFound' does not exist in the current context
The name 'Ok' does not exist in the current context
The first error can be solve with System.Web.Http.IHttpActionResult.
Because can't add using System.Web.Http;
because create conflicts with using System.Web.Mvc;
I saw a couple of related question:
Like this IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet) ISSUE but this use a JSonResult
And this one How to return JSON in a ASP.NET MVC/web controller? but this use a Task<ActionResult>
And neither handle the case when the object is not found.
Questions:
Is there a reason WebApi controller doesn't need convert the result to JSON but an ASP.NET MVC controller does? Because my jQuery can read it just fine.
Can I convert my WebApi code to ASP.NET MVC or need to use one of the examples?
Do I need the
Not Found
result ?