I have a country field and a state field. I want to show the state field when the user chooses United States. Otherwise, I want it to be hidden.
This is my cshtml page of the form.
<div >
<label asp-for="Form.Country" ></label>
<select asp-for="Form.Country" >
<option disabled selected>Choose your Country</option>
<option>Canada</option>
<option>United States</option>
<option>Mexico</option>
</select>
<span asp-validation-for="Form.Country" ></span>
</div>
<div >
<label asp-for="Form.State" ></label>
<select asp-for="Form.State" asp-items="Model.States" >
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" ></span>
</div>
<div >
<label asp-for="Form.City" ></label>
<input asp-for="Form.City" />
<span asp-validation-for="Form.City" ></span>
</div>
I tried searching for a solution, but most involve using JS which I don't know and don't want to use now.
I know razor is server side code, but maybe I can integrate a blazor component or use css to achieve this.
CodePudding user response:
I'm very glad to see you can receive to use javascript to do it, Here is a simple demo with annotations, I hope it can solve your issue.
add a onchange()
method on the first dropdown list:
<select asp-for="Form.Country" onchange="Select()">
add an Id for the second dropdown list:
<div id="demo">
.........
</div>
Then write a javascript in your view:
@section scripts
{
<script>
function Select(){
//get the element by id
var select = document.getElementById("Form_Country");
//get the option's text
var index = select.selectedIndex;
var text = select.options[index].text;
//if option's text is not United States, hide the second dropdownlist.
if(text!="United States"){
//hiden the dropdownlist
document.getElementById("demo").style.display='none';
}else{
//show the dropdownlist
document.getElementById("demo").style.display='block';
}
}
</script>
}
CodePudding user response:
I think this is what you're looking for
@if (Form.Country == "UnitedStates")
{
MARKUP FOR STATE DROPDOWN
}