ViewBag and ViewData

0

I'm starting a career in development, and in the project here, I found a ViewData being used, and through my searches I can not update it in a ActionResult in the controller. I ended up testing with a ViewBag too, where I was also unhappy. Remembering that the value of these two will be allocated in page rendering, correct? (Correct me, please)

How could I do to retrieve this values, via ajax , to another question, since my .js functions are in another file, not located within 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;
}

Soon after in my Index game the value of ViewData in an input hidden, where I can work in my .js file quietly. But I see I can better this way, just do not know how.

    
asked by anonymous 27.03.2018 / 16:13

1 answer

0

The values of ViewData , ViewBag or even TempData can not be accessed in the javascript file, which makes it difficult to use later on a Ajax call.

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

file.cshtml :

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

OtherFile.js

$.ajax({
   url: 'http://blablabla.com.br',
   data: {
      valor: valorDaController 
   }, ....
    
28.03.2018 / 03:53