Search code examples
javascriptc#razorkendo-dropdown

How to post input fields conditionally


I have an MVC (Razor) web app. The form has 2 fields, one dropdown box (Kendo) and one input field for a date.

After the user makes a change on the dropdown, my 2nd input field is enabled or disabled based on the chosen type in the dropdown box. When the input field is disabled I fill the input with a default value.

When the user submits the form, I only get 2nd form field value posted in the viewmodel when the 2nd field is enabled, when disabled the value is not posted. I know this a common pattern in HTML, that disabled fields are not part of the POST.

My question: how can I solve this issue to get the value POSTed when the field is disabled ? It should be done in JS...


Solution

  • Fixed it, in the onchange handler of the dropdown box attach this JS code:

    var defaultDateValue = "2017-01-04"; //just for demo
    var $effectiveToInput = $("#@Html.IdFor(m => m.EffectiveToDate)");
    $effectiveToInput.parent().append("<input type=\"hidden\" name=\"@Html.NameFor(m => m.EffectiveToDate)\" id=\"@Html.NameFor(m => m.EffectiveToDate)\" value=\"" + defaultDateValue +"\" />");
    

    And for the other types, i clear the hidden fields with checks:

    function removeHiddenEffectiveToDateField() {
        var $effectiveToInput = $("#@(Html.IdFor(m => m.EffectiveToDate))[type = hidden]");
        if (null !== $effectiveToInput) {
           $effectiveToInput.remove();
        }
     }