MVC3/4 Validating Hidden Fields

。_饼干妹妹 提交于 2019-11-28 06:03:55

问题


I have set up model validation for my form but validation doesn't seem to work at all. I don't suppose anybody can help. I've tried using the below work-around but that keeps pulling up an 'undefined' error in firebug.

Example Work-Around Script:

<script type="text/javascript">
    $(document).ready(function () {            
        $.validator.setDefaults({ ignore: [] });
    });
</script>

Example Text Field (Note: autocomplete text field with name of customer):

    @Html.TextBox("txtCustomer", null, new { @id = "txtCustomer", @class = "txt" })

Example Hidden Field (Note: When selection is made from the autocomplete field, the id is injected into the hidden field):

    @Html.HiddenFor(model => model.Customer_ID, new { @id = "hCustomerID" })

Example Model Data Annotation

    [Range(1, Int32.MaxValue, ErrorMessage = "Please select a customer")]
    public int Customer_ID { get; set; }

EDIT: Screenshot of errors

Sorry i have to post links to the screenshots because my rep points are high enough.

UI Postback Error

EDIT: Screenshot showing page source

Screenshot of Page Source


回答1:


Its too late to change the ignore on the validator in this way after the unobtrusive script. This is because the validator only pulls in the defaults once - when it is created. The unobtrusive script creates the validator for you. You need to reference the existing validator object and update it.

try this

<script>
    $(document).ready(function () {            
        $('form').validate().settings.ignore = []
    });
</script>



回答2:


If you don't have to use javascript, in your Controller, and in your action of the related view, you can add a model error before validating your model. Example:

 [HttpPost]
        public ActionResult Fix(YourModel mdl)
    {
        if (mdl.Customer_ID>Int32.MaxValue || mdl.Customer_ID<1)
            ModelState.AddModelError("", "Your error message!");

        if (ModelState.IsValid)
        {


           //
           //Some code
           //

            return View("YourView", yourlist);
        }

        return View(mdl);
    }


来源:https://stackoverflow.com/questions/14503698/mvc3-4-validating-hidden-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!