How to deal with Validation when filtering dropdow

2019-09-05 03:58发布

问题:

I have a form with 2 dropdowns. The first filters the second. Therefore when a selection is made from the first dropdown I need to postback to the controller to repopulate the second dropdown. Since the second dropdown is a required field, I get the validation triggering each time I autopostback from the first dropdown. I am using JS to do this "autopostback".

        <script type='text/javascript'>
        $('#StdThemePropertyId').change(function () {
            $(this).parents('form').submit();
        });
    </script>

What would be a recommended approach to solving this please.

Thanks.

回答1:

In this case your Json format should look like this:

Controller

public ActionResult YourActionMethod(int id) 
{ 
   return Json(new {
               yourTitle="AAA", 
               yourValue="BBB"
         });
}

JS

<script type="text/javascript">

    $('#StdThemePropertyId').change(
      $.getJSON("../YourActionMethod", function(data){
        $.each(data, function(yourTitle, yourValue) {
          $('#yourDropDownList').append(
            $('<option></option>').val(yourTitle).html(yourValue)
          );
        });
      });
    });

</script>

If this helps you, mark as correct!



回答2:

You should try using ajax that might help.

<script type="text/javascript">

        $('#StdThemePropertyId').change(

            $.ajax({
                url: 'url.php',
                success: function(data) {
                    $('#StdThemePropertyId').html(data);
                }
            });
        }

    });
    </script>

"data" is your return value after it has been parsed in url.php. Hope this helps. :)



回答3:

You should have something like this:

Controller:

public ActionResult YourActionMethod(int id) 
{ 
  return Json(new {foo="AAA", bar="BBB"});
}

Javascript:

<script type="text/javascript">

    $('#StdThemePropertyId').change(

        $.getJSON("../YourActionMethod", {
            id: someId
           }, function(data) {
                alert(data.foo);
                alert(data.bar);
               //here fill in your dropdownlist
           });
    }
});
</script>'

Hope it helps!



回答4:

Your problem is submitting the form on the onchange function. That automatically validates the form if i'm correct



回答5:

You shouldn't postback your whole form. You should make an AJAX call to fetch the values and populate the second dropdownlist. It'd solve your problem.