Set model property in javascript variable

Asked

Viewed 632 times

1

I have an Action Usuario that displays user details among other actions that can be performed. I also have a code javascript that needs in some part to set a model property in the javascript variable. Follow the code below:

@model Aprendendo.Asp.Net.Model.Usuario
//Códigos html
<script type="text/javascript">
    var idUsuario = @Model.Id;
    //Demais códigos
</script>

But this way is not working. What to do in this situation?

2 answers

4

Place the model value in a hidden field (input type="hidden") and then assign the value of this hidden field in the Javascript variable.

Razor code:

<input type="hidden" id="codigo" value="@Model.Id" />

Javascript code:

var id = $("#codigo").val();

2


Quotation marks on your property, as an example below

 @model Aprendendo.Asp.Net.Model.Usuario
 //Códigos html
 <script type="text/javascript">
  var idUsuario = '@Model.Id';
  //Demais códigos
 </script>
  • But this does not work when the Javascript code is in a file external to the view, because Javascript does not recognize the Razor syntax.

  • 1

    That’s right Ulysses, in this case it would be better to use your solution presented below

  • Yeah, @John Alex. But in cases similar to the question, where the Javascript code is declared in a Script within a View, your solution fits perfectly as well.

Browser other questions tagged

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