Viewbag and Viewdata Doubt

Asked

Viewed 606 times

0

I’m starting my career in development, and in the company project here, I found a ViewData being used, and for my researches I can not update it in a ActionResult in the controller. I ended up testing with a ViewBag also, where I was also unhappy. Remembering that the value of these two will be assigned in the page rendering, correct? (Please correct me)

How could I do to recover this values, via ajax, until another question, because my functions . js are in another file, not located within the Index.cshtml

Edit 1: In my current scenario, the following is happening:

public IActionResult Index()
{
   // Crio minha ViewData
   ViewData["NomeDaViewData"] = null;
   UpdateViewData(); // aqui onde vou atualizá-la

   return View();
}

private void UpdateViewData()
{
   var dado = _myReposiory.BuscaValor();
   ViewData["NomeDaViewData"] = dado;
}

Right after in my Index I play the value of Viewdata in a Hidden input, where I can work in my file . js quietly. But I see I can better this way, I just don’t know how.

  • when you say "via ajax," you mean javascript needs a value that has been passed down ViewData or ViewBag that’s it?

  • You want to pass the value of the ajax in the View to the Controller?

  • That’s right @Ricardopunctual.

  • I would like to pass a value that is in my Controller to my View @Robsonoliveira

1 answer

0


The values of ViewData, ViewBagor TempData cannot be accessed in the file javascript, which makes further use of a Ajax.

One solution is to read in the file .cshtml, and put in a javascript variable, which can be accessed later by your file, for example:

cshtml file:

<script type='text/javascript'>
  var valorDaController = '@ViewData["Valor"]';
<script>

otherArchive.js

$.ajax({
   url: 'http://blablabla.com.br',
   data: {
      valor: valorDaController 
   }, ....
  • Thanks man!! Another solution that the staff indicated me here, was to put the value inside a Hidden input, then I can access from anywhere

  • 1

    Good, the important thing is to know that you should do it in .cshtml

Browser other questions tagged

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