Hi I am still very new to web design and languages including JavaScript.
In a strongly typed cshtml view, is it possible to only show a textfield based on a checkbox (where both the textfield and the checkbox are strongly typed to the model?) I created a example scenario below:
Sample Class:
namespace FruitSurveyNameSpace
{
public class FruitSurvey
{
public bool likesFruit { get; set; }
public string fruitName { get; set; }
}
}
Sample cshtml:
<!DOCTYPE html>
@using FruitSurveyNameSpace
@model FruitSurvey
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<p>Like Fruit? @Html.EditorFor(model => model.likesFruit) </p>
<p>Which Fruit: @Html.EditorFor(model => model.fruitName)</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
which generates the following html
<form action="/" method="post">
<input name="__RequestVerificationToken" type="hidden" value="blahValue" />
<fieldset>
<legend>Survey</legend>
<p>likesFruit?
<input class="check-box" data-val="true" data-val-required="The likesFruit field is required." id="likesFruit1" name="likesFruit1Name" type="checkbox" value="true" />
</p>
<p>fruitName
<input class="text-box single-line" id="fruitName1" name="fruitName1Name" type="text" value="" />
</p>
</fieldset>
</form>
As in the sample scenario above, it only makes sense for the user to input the fruit name once he/she selects that he/she likes fruit (dynamically). Otherwise, the fruit name input doesn't have any meaning and should not be displayed. Furthermore, we probably enforce the user to input the fruit name once the he/she selects like fruit checkbox (currently I am using [Required] attribute in non dynamically generated fields and not sure if it would still work if becoming dynamic).
As we can see, both values are strongly typed to the model, and that's why I'm using html helpers. Is there a way to do so without using JavaScript? Or if there isn't, how should I do so in combination with html helpers?
Many thanks in advance.