2

I have an assignment where I have to implement the dropdown for the US states if the 'United States' is selected in the countries dropdown.

For that I implemented two controls, the textbox for non us states and the dropdown for the us states

        <input class="form-control" type="text" asp-for="BIS232Request.JSONData.RequestingOrg.State" />
        <select class="form-control" asp-for="BIS232Request.JSONData.RequestingOrg.State" id="HeadquartersState"></select>
        <span asp-validation-for="BIS232Request.JSONData.RequestingOrg.State" class="alert-danger"></span>

However, there is only one model property for the state

[Required]
[DisplayName("State")]
public string State { get; set; }

How can I reference and properly validate the state accounting for both the textbox and the dropdown

Thank you very much for your help!

James
  • 1,081
  • 4
  • 15
  • 34
  • The usual, can you show us what you have tried, and what errors/issues you are having? If it's an assignment, you might want to talk to your fellow student or your professor. – Trey Nov 01 '18 at 13:33
  • Possible duplicate of [MVC6 Dropdownlist of Countries](https://stackoverflow.com/questions/34738481/mvc6-dropdownlist-of-countries) – Christian Gollhardt Nov 01 '18 at 13:33

1 Answers1

2

The issue is simply that the values for both the input and the select are being posted and one will always overwrite the other in the post data. You'll need to add some JavaScript to disable one or the other based on the country. If either the input or the select have the disabled attribute, it will not post its value, leaving only the value of the other.

$('[name$=Country]').on('change', function () {
    if ($(this).val() === 'US') {
       $('select[name$=State]').removeAttr('disabled');
       $('input[name$=State]').attr('disabled', true);
    } else {
       $('input[name$=State]').removeAttr('disabled');
       $('select[name$=State]').attr('disabled', true);
    }
});
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444