user1790300
user1790300

Reputation: 1735

MVC 3: Show/Hide logic for loading form elements via ajax

I am currently designing a web application using mvc 3 and c#. I have to do the following scenario and am trying to determine what the correct implementation would be for the platform. Here we go, I have to show/hide several form elements(textboxes) depending upon the selection of a dropdown list, which should also be a part of the form. What would be the best way to implement this under the mvc 3 platform. One major issue I have is that all of the elements that should appear, should also be required as well and the others should not be required. I would prefer to use DataAnnotation validation. Should I initially render all of the form elements and use javascript to determine which ones to show/hide based upon dropdown selection? The issue here seems to be how do I vary the required logic while maintaining the validation logic that makes sure that if anything is entered in any field, it is validated? On the other hand, it seems like overkill to create a partial view for each form that is needed and show/hide the partial view based upon dropdown selection, not to mention inefficient due to the rountdrips.

Upvotes: 0

Views: 2455

Answers (2)

skub
skub

Reputation: 2306

Perhaps you could do this on the front end with jQuery. Eg

<select name="source" id="source">
  <option value="null" selected="selected">&mdash;Select&mdash;</option>
  <option value="o1">Option 1</option>
  <option value="o2">Option 2</option>
  <option value="o3">Option 3</option>
</select>

<div id="content"> some content to show/hide </div>

And the corresponding jquery:

$('#source').change(function() {
    ($(this).val() == "o3") ? $('#content').show() : $('#content').hide();
});

So basically when some selects option 3, the div content will displayed. I am not sure why you would need to use ajax, but you can just validate the values on the server side once the data has been submitted.

Also might be beneficial to look at conditional validations using the Mvc.ValidationToolkit:

Upvotes: 1

Related Questions