Update a viewbag (c# Razor) with a javascript variable

Asked

Viewed 901 times

0

Maybe what I want to do may be impossible, because of server and browser side issues, but I would like to do the following:

<script>
    function pegarId(id) {
        $('@ViewBag.Id').value = $(this).attr("id");        
    }
</script>

Thanks in advance, any hint or help.

  • 1

    Can’t do that. To communicate between browser and server you have to use http requests (or Formulary submissions, or AJAX requests).

  • You want to select the element according to what is stored in ViewBag, or wants to assign a value to ViewBag.Id?

  • Could you give more details than you want to do? It got a little confused what you’re asking for.

  • @Lucas tries to edit your question and describe a little better your purpose, that maybe we can help you with a better solution to your problem.

  • Could you tell us what scenario you are trying to use? It would be easier to find a better solution to help you.

1 answer

1

Can’t change Viewbag from Javascript since Viewbag is a feature that works entirely on the server side.

Otherwise, however, it is possible: you can define a javascript variable that receives a value that will be written from Viewbag during the View rendering. Something like:

<script>
    var umaVariavel = @ViewBag.MeuValor
</script>
  • thanks a lot!

Browser other questions tagged

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