Can We Use C# Code In Javascript
Today, I want to mention about a problem I was ran into. I had to get a variable in my javascript code in my Asp.Net MVC web project. And I try to do it and make a lot of search about this topic. At the end, I realise that it was impossible in a direct way. But you can do it like following code.
1 2 3 4 5 6 7 |
<input type='button' onclick="MyFunc('@Model.Property')" /> <script type="text/javascript"> function MyFunc(somethingPresented) { alert(somethingPresented); } </script> |
So you cannot pass the variable directly, but you can do it in indirect way. Another method to get your model’s properties should be by wrapping property assignment in Quotes.
1 2 3 4 5 |
var Name = '@Model.Name'; var Age = '@Model.Age'; var LoginTime = '@Model.LoginDateTime'; var IsAuthenticated = '@Model.IsAuthenticated'; var IconHtml = '@Model.UserIconHTML'; |
You should have a look at my another post about When To Use Try-Catch In C#
If you have question do not forget to write from the chat button next to it or from the comment.
Recent Comments