houman_ag houman_ag - 2 months ago 9
Javascript Question

Accessing a view model element through Javascript

I am passing a Model to my view that is called HomeViewModel. The HomeViewModel has a bool property called isNext. In my view, I simply want to display the isNext value. So basically I have this:

@model Impoware.Models.HomeViewModel

@{
ViewBag.Title = "View Contest";
}

<h2>View Current Contest</h2>

@using (Html.BeginForm())
{
<table>
<tr>
<td>@Html.LabelFor(m => m.isNext)</td>
<td></td>
<td align="right">Submenu goes here</td>
</tr>
</table>
}


In the same view, I have a simple div that onclick calls setIsNext(true). Essentially I want to set the value of isNext to true/false based on what is clicked but seemingly javascript cannot find the elemntbyId('isNext') (alert('2') never gets called). Any ideas?

<script>
var setIsNext = function(input){
alert(input);
var output = document.getElementById('isNext');

if (output != null) {
output.innerHTML = input;
alert('2');
}
}
</script>

Answer

You will need to specify ID in the View file

// in cshtml

@Html.LabelFor(m => m.isNext, new { id = "MyNextId" })


var output = document.getElementById('MyNextId');