Reputation: 59
Example :
<script type="text/javascript">
function abc() {
var t = document.getElementById("name").value;
@foreach(Player pl in Model){
if (t == pl.Name) {
alert("This name is already use!");
}
}
</script>
Error : t - cannot resolve symbol How can i use JavaScript variable in C# code? Is it possible in this example?
Upvotes: 0
Views: 181
Reputation: 5919
You may do something like this.
<script type="text/javascript">
function abc(players) {
var t = document.getElementById("name").value;
for(p in players) {
if (t == p.Name) {
alert("This name is already use!");
}
}
abc(@Html.Raw(Json.Encode( Model )));
</script>
Upvotes: 0
Reputation: 2852
You cannot use JS variables in C# code , but you can use C# variables in the code. In most cases C# is used to render HTML or JS.
In your case it would be best if you render your C# serverside model as a JS array , which you can later on iterate.
make an action that returns your list (assuming it's a list) as a JSON
Cheers!
Upvotes: 2