Viewbag, passing controller value to Razor page

Asked

Viewed 470 times

-1

I have this Ajax to be able to take the data and pass to the function Save items that is in the Schedulesitenscontroller, that even works perfectly.

function SalvarItens() {
var idItem = $("#idItem").val();

if (idItem == 0) {
    var dataInicio = $("#txtHoraInicio").val();
    var dataFim = $("#txtHoraFim").val();
    var tipoLimite = $("#txtTipoLimite").val();
    var limiteAcessos = $("#txtLimiteAcessos").val();
    var cbSeg = $('#cbSeg').prop('checked');
    var cbTer = $('#cbTer').prop('checked');
    var cbQua = $('#cbQua').prop('checked');
    var cbQui = $('#cbQui').prop('checked');
    var cbSex = $('#cbSex').prop('checked');
    var cbSab = $('#cbSab').prop('checked');
    var cbDom = $('#cbDom').prop('checked');
    var cbFer = $('#cbFer').prop('checked');
    var idHorario = $("#idHorario").val();
    var url = "/HorariosItens/SalvarItens";

    $.ajax({
        url: url
        , data: { HoraInicio: dataInicio, HoraFim: dataFim, Seg: cbSeg, Ter: cbTer, Qua: cbQua, Qui: cbQui, Sex: cbSex, Sab: cbSab, Dom: cbDom, Fer: cbFer, Tipolimite: tipoLimite, Limiteacessos: limiteAcessos, HorarioId: idHorario }
        , type: "POST"
        , datatype: "html"
        , success: function (data) {
            if (data.resultado > 0) {
                //console.log(data.resultado);
                ListarItens(idHorario);

            }
        }
    });
} 

Here is the function that saves the time item:

public async Task<ActionResult> SalvarItens(Horarios h, string HoraInicio, string HoraFim, bool Seg, bool Ter, bool Qua, bool Qui, bool Sex, bool Sab, bool Dom, bool Fer, int Tipolimite, int Limiteacessos, int HorarioId)
{
    h.Id = HorarioId;
    var item = new HorariosItens()
    {
        HoraFim = HoraFim,
        HoraInicio = HoraInicio,
        Seg = Seg,
        Ter = Ter,
        Qua = Qua,
        Qui = Qui,
        Sex = Sex,
        Sab = Sab,
        Dom = Dom,
        Fer = Fer,
        Tipolimite = Tipolimite,
        Limiteacessos = Limiteacessos,
        HorarioId = HorarioId,

    };
    ViewBag.idHorario = HorarioId;
    _context.HorariosItens.Add(item);
        _context.SaveChanges();



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

On the create page, in this method, I try to get the value of idHorario, but it is always coming in null. And this is where he’s like "Load" on the page.

public async Task<IActionResult> OnGetAsync()
{
    var viewDataVariavel = ViewData["idHorario"];
    if(viewDataVariavel != null)
    { 
        HorariosItens = await _context.HorariosItens
                .Include(a => a.Horarios).Where(a => a.HorarioId == int.Parse(viewDataVariavel.ToString())).ToListAsync();
    }
    else
    {
        HorariosItens = await _context.HorariosItens
            .Include(a => a.Horarios).Where(a => a.HorarioId == 0).ToListAsync();
    }
    return Page();
}

I have tried several ways, but none comes with value, I need to click with the value. I have the pageRazor Create de Horario item, on it I create, and I have the table, which in case should update, after including the time item. I don’t know if you can understand, is that the Pagerazor I can not create the view design, the same when MVC is used without Core. So I’m doing it this way.

o Listaritens, is this function in ajax:

function ListarItens(idHorario) {

var url = "/HorarioItem/Create";

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

    }
});

}

Edit:

Every time I include a new time item, it enters this function:

 public async Task<IActionResult> OnGetAsync()
    {
        HorariosItens = await _context.HorariosItens
       .Include(a => a.Horarios).Where(a => a.HorarioId == 0).ToListAsync();
        return Page();
    }

if I pass the a.HorarioID == "Numerodoidaqui" without being the variable, it loads, I need to pass the variable in this function.

  • Mariana, do not use the Snippet for non-html/JS/CSS code in a full example. For all others, use the button {} of the editor.

  • Why do you want to get the idHorario value in the Ongetasync method? The purpose is not to access the Viewbag in the View?

  • I use pageRazor @Perozzo, his controller is very confusing to tell you the truth, I use json to save in the bank, and in the same ajax I call the save items, and then I need after saving is loaded the table, which is on the same page.

  • You are returning Result = item. Id in Save Items, should not be item.Horarioid?

  • No, because in the time items I load all the time items Where idHorario = item.HorarioId. Are several items for a time.

  • Viewdata and Viewbag serve to send Controller information to View, not the other way around

  • I just need the table to be loaded with the time id, the Pagerazor is very complicated, I’m not able to do it that way, either by ajax, on the same page.

  • I updated my answer, could you check? Thank you

  • I updated again; now, I think it’s definitive! :)

  • I added another hint to my reply!

Show 5 more comments

1 answer

0

How about trying the following:

var viewDataVariavel = ViewBag.idHorario;

EDIT: I saw that you updated with JS, but I still have a question (sorry),

 $.ajax({
    ...       
    , success: function (data) {
        if (data.resultado > 0) {
            //console.log(data.resultado);
            ListarItens(idHorario);
        }
    }
});

Could update with the declaration of function ListarItens(idHorario)? Thank you.

EDIT 2: I think I understand what you want to do; do it like this: on the C#, on Task<ActionResult> SalvarItens(...), in place of

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

exchange for

return new JsonResult(new { horarioId = HorarioId });

And on the JS side, on function SalvarItens(), barter

$.ajax({
    ...
    , success: function (data) {
        if (data.resultado > 0) {
            //console.log(data.resultado);
            ListarItens(idHorario);
        }
    }
});

for

$.ajax({
    ...
    , success: function (data) {
        if (data.horarioId) {
            ListarItens(data.horarioId);
        }
    }
});

Be careful that variable names and object properties are box sensitive, in JS!

EDIT 3: in public async Task<ActionResult> SalvarItens(Horarios h, ...), withdrawing Horarios h:

public async Task<ActionResult> SalvarItens(string HoraInicio, string HoraFim, bool Seg, bool Ter, bool Qua, bool Qui, bool Sex, bool Sab, bool Dom, bool Fer, int Tipolimite, int Limiteacessos, int HorarioId)
{
    //h.Id = HorarioId;
        ...
}
  • This way he returns to me that Viewbag does not exist in the current context.

  • And change ViewBag.idHorario = HorarioId; for ViewData["idHorario"] = HorarioId;, in the controller?

  • Just out of curiosity: what version of ASP.NET MVC you are in?

  • There is something strange there; the method SalvarItens returns a JsonResult... There is no way to transpose the id you want without returning a View, unless you pass the id by JsonResult: return new JsonResult(new { Horario = HorarioId, Resultado = item.Id }); and later use code to get it.

  • Sorry Marcelo, I did not leave very well explained, what happens is that I work with Razorpages, I have a create page that creates the time name, and then in the json I call the div with the item create, and I create, and I need to update the table, so I need to pass the id, to load, I’m seeing courses, and searching on the internet, but I’m not able to solve this problem.

  • I need that after creating the item schedule, it updates the table, which is on the same page, if you have any better way, or other idea, thank you, I can hardly find examples on the internet.

  • How is the JS code dealing with the return of SalvarItens?

  • I would need to understand how and what receives the return of SalvarItens, otherwise it becomes difficult to explain! :(

  • I updated the question, explaining all the processes, I hope you can understand :D

  • I updated the response rs

  • Right! I also updated mine.

  • It continues without updating the table. :(

  • Marcelo added the method that he enters every time he loads the page, could I create another method and call him ? Something similar, I’m still learning the language, I don’t have much knowledge.

Show 9 more comments

Browser other questions tagged

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