Search code examples
model-view-controllerunobtrusive-javascriptremote-validation

Remote validation causes submit inputs (multiple-submit-buttons) to be null


I recently implemented remote validation in my form:

ViewModel:

[Remote("IsTagUnique", "myController", "myArea", ErrorMessage = "This tag already exists.")]
public string tag { get; set; }

Controller:

        public ActionResult IsTagUnique(string tag)
        {
            using (db)
            {
                try
                {
                    var myTag = db.ASAuftraege.Single(m => m.tag == tag);
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }                        
                }
                catch (Exception)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult myView(string Send){ 
            // doSomething 
        }

View (called "myView")

@Html.TextBoxFor(m => m.tag) @Html.ValidationMessageFor(m => m.tag)


<button class="form-button-submit" type="submit" name="Send" value="Send">Send</button>

The validation works perfectly fine.

Problem is: When I click the Send-button without manually triggering the validation on the tag-field once by clicking into the field and then clicking somewhere else the "IsTagUnique" function is executed before the myView()-function. This causes my submit-inputs (I actually have multiple send-buttons, just like the one shown in the view (different name/value of course) to be null. Any idea what I can do? I tried triggering the validation manually by giving focus and blurring the tag-field, and by triggering a change event. Doesn't trigger the validation, though.


Solution

  • After searching for a while I found out this seems to be a known bug:

    The issue happens when a form which uses the remote method to validate a field. If a submit button is pressed after the validator fires, everything is alright and the request will contain the clicked submit button name/value pair. However, when the remote method is not fired before the submit button is pressed, then the resulting request will NOT contain the submit button value/pair.

    A solution that worked for me is this one:

    $(function() {
    $('button[type=submit]').click(function () {
        $('<input>').attr({
            type: 'hidden',
            name: this.name,
            value: this.value
        }).appendTo($(this).closest('form'));
    });
    });
    

    Credit to arturoribes