You are mixing the functions in the controller, to use json in a method you must use Jsonresult as the return type identifier. In Asp.net mvc there are two ways to make an Ajax call and with that have a record or a list of records in json, follow two examples that calls in the same controller so you have 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 I want to create html elements dynamically, mount a table, for example, and show to 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 I don’t want to reflesh on the whole page, for example, add an item in a cart in a virtual store. Anyway, depending on the form 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>
Json is for everything but what you want: display on screen.
– Leonel Sanches da Silva
and what alternative I would have to show the Json data?
– Fabio Souza
The idea would be to feed some screen element with Json. For example, a JS component, or even a popular HTML element using JSON data. For example: http://stackoverflow.com/questions/18484762/populating-drop-down-with-json-object
– Leonel Sanches da Silva