You are mixing the functions in the controller, so if you use json in a method you should use JsonResult as the return type identifier. In asp.net mvc there are two ways to make an Ajax call and with this having a record or a list of records in json, there are two examples that make call in the same controller so that it has a better understanding:
Controller:
[HttpPost]
public async Task<JsonResult> JsonX()
{
var frente = (from d in db.Imagem
orderby d.IdImagem
select new
{
d.IdImagem,
d.EnderecoImagem,
d.DescricaoLegenda,
d.CorFundoLegenda,
d.Descricao,
d.Largura,
d.Altura,
d.DescricaoAlternativa,
});
return Json(await frente.ToListAsync());
}
Ajax call option 1 - I use in situations where I want to dynamically create html elements, set up a table, for example, and show the user:
<script type="text/javascript">
$.ajax({
url: "/ControllerX/JsonX",
type: "POST",
ifModified: true,
cache: true,
async: true,
dataType: "json",
success: function (data) {
if (data.length > 0) {
var linha = "";
for (i = 0; i < data.length; i++) {
linha += data[i] + "<br>";
}
}
});
</script>
Ajax Call Option 2 - I use more in situations that I do not want to reflesh on the whole page, for example, adding an item to a cart in a virtual store. Anyway, depending on the way you do you can use both forms for the same purpose:
<form class="form-inline" method="post" action="/ControllerX/JsonX" data-ajax="true"
data-ajax-failure="FalhaAjax" data-ajax-success="SucessoAjax">
<div class="form-group">
<div class="col-sm-6">
<input class="input-sm form-control" type="submit" />
</div>
</div>
</form>
<script type="text/javascript">
function SucessoAjax(data) {
if (data.length > 0) {
var linha = "";
for (i = 0; i < data.length; i++) {
linha += data[i] + "<br>";
}
}
}
function FalhaAjax(data) {
alert("erro");
}
</script>