AJAX function does not pass output to another function

Asked

Viewed 49 times

0

I have this function in AJAX:

function SalvarHorario() {


    //NomeHorario
    var nome = $("#Nome").val();

    var token = $('input[name="__RequestVerificationToken"]').val();
    var tokenadr = $('form[action="/Horario/Create"] input[name="__RequestVerificationToken"]').val();
    var headers = {};
    var headersadr = {};
    headers['__RequestVerificationToken'] = token;
    headersadr['__RequestVerificationToken'] = tokenadr;

    //Gravar
    var url = "/Horario/Create";

    $.ajax({
        url: url
        , type: 'POST'
        , headers: headersadr
        , data: { Id: 0, Nome: nome, __RequestVerificationToken: token }
        , success: function (data) {
            if (data.Resultado > 0) {
            ListarItens(data.Resultado);
            //    alert(data.Resultado);
            }
        }
    });
}

The result is correct, is getting the right ID, but it does not pass to the function Listaritens, I have done so in other projects, and worked well, he understands that it is not higher than 0, and in the console, the result gets the last ID inserted correctly, how can I proceed? I’ve tried many ways, and no one passes the correct ID.

This is the list of items:

function ListarItens(idHorario) {

    var url = "/HorariosItens/ListarItens";

    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idHorario }
        , datatype: "html"
        , success: function (data) {
            var divItens = $("#divItens");
            divItens.empty();
            divItens.show();
            divItens.html(data);
            $("#idItem").val("0");
        }
    });

}

Where I need that function:

 public ActionResult ListarItens(int id)
        {
            var lista = _context.HorariosItens.Where(m => m.Horarios.Id == id);
            ViewBag.HorarioId = id;
            ViewBag.ItemId = 0;
            return PartialView(lista);
        }

I believe the problem lies in the date. Result, because it is not passing, if I put an Alert, it returns me Undefined, but is included successfully, so much so that it passes from Success: Function (date).

Create time:

 if (ModelState.IsValid)
            {
                _context.Horarios.Add(h);
                _context.SaveChanges();
            }

            return new JsonResult(new { Resultado = h.Id });

  • Post the code of Listaritens.

  • I updated the question.

  • It would be possible to add the code of Horario/Create?

  • Edited the question, remembering that it saves in the normal bank with the function.

  • Got a little confused the explanation, I understood that it inserts normally, but the return date. Return is Undefined?

  • Yes, it inserts normal, ai when it has if (date.Result > 0) { it does not enter, but in the console, it shows the value of the correct result.

  • Using Asp.net core and Razors pages.

  • I’m not sure if this could be it, but I believe the problem lies in the return JsonResult. Change your method to one ActionResult and in return a return Json(new { Resultado = h.Id });

  • It is already action result, when I put the Json it returns this error. Type or namespace name "Json" cannot be found (using a directive or Assembly reference is missing?)

  • When I see it on the browser network, it appears {result: 278}, but I added this code to the function, console.log(data.result); console.log(date.Result); and the two appear Undefined.

  • Aaaah.. you who was having problems returning Json.. So, There’s something wrong there, this code is in a controller right? What is this controller is inheriting?

  • Please try console.log(date.result) with R minuscule

  • Right in the browser, it returns the following error: Uncaught Referenceerror: data is not defined at <Anonymous>:1:13 . Create is not in a controller, the rest are.

  • Not directly in the browser but in its function. in the browser this variable no longer exists, or better, change ListarItens(data.Resultado); for ListarItens(data.resultado); Don’t forget the ctrl+f5 to clear the cache

  • @Barbetta now in the console it appears the id correctly, and enters the function, but public Actionresult Listaritens(int id) now it returns me error in this function, in this first line. the ID is being passed.

  • @marianac_costa the error in the list should be another, because it does not enter that function if you do not pass some number

Show 12 more comments

1 answer

1


The problem occurred because by default the returns from json no. NET Core are in Camel Casing, and the first letter is lowercase.

One way to break this is in Startup.cs "inform" that you want the json be as written in variable. The code for this would be:

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    }); 

Another solution, as commented, is to wait for the returns to be in Camel Casing, that is to say, Return will come return

You can see more about Camel Casing at that link

Browser other questions tagged

You are not signed in. Login or sign up in order to post.