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 <div>
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>
LabelFor
is going to render a label for your property name, not the value of that property. If you want to set the value of that so that when the form is submitted ,the updated value is available, you should use an input field. If you do not prefer to show a visible input field, you may consider using a hidden field.
@using (Html.BeginForm())
{
<table>
<tr>
<td> @Html.HiddenFor(f=>f.isNext)</td>
<td align="right">Submenu goes here</td>
</tr>
</table>
<div class="myDiv" data-val="true">Yes</div>
<div class="myDiv" data-val="false">No</div>
}
And you can read the data-val attribute value of the clicked button and set that to the hidden input.
$(function () {
$(".myDiv").click(function(e) {
$("#isNext").val($(this).data("val"));
});
});
Also, If you prefer to have a checkbox in the UI for the boolean property and want to update the value of that based on the div click, you can do this.
@using (Html.BeginForm())
{
@Html.CheckBoxFor(f=>f.isNext)
<div class="myDiv" data-val="true">Yes</div>
<div class="myDiv" data-val="false">No</div>
}
and when the div is clicked you need to update the checked status as well
$(function () {
$(".myDiv") .click(function (e) {
var v = $(this).data("val");
$("input[name='isNext']").val(v);
$("#isNext").attr("checked", v);;
});
});