MVC validator errors disappear by time management

I have a simple model FilesModelfor updating a line Descriptionand a boolean flag value Archivedfor several (already loaded) files, and FilesModela checker FilesModelValidatorthat starts when this data is published. This validator does nothing more than verify that each file has a description. I know that it works and correctly returns an error for empty descriptions based on my debugging so far.

However, when control is passed to the Action method in the controller, ModelState is different from what I expect. There are no errors in the description fields, but for each checked flag there is one error: "The value 'on' is not valid for archived".

This kind of validation works fine in other areas of the site, so I'm sure there is some minute that I miss. Any suggestions as to why this might happen and how to fix it?

validator

public FilesModelValidator()
{
    RuleFor(f => f.Files)
        .Must(AllHaveADescription).WithMessage("Must have a description");
}

public static bool AllHaveADescription(Files files)
{
    // This is run on postback, and returns false when any Description is empty
    return files.All(f => f.Description != null && f.Description.Length > 0);
}

controller

[HttpPost]
public virtual ActionResult Update(FilesModel model)
{
    // At this point, ModelState contains an error for each checked checkbox
    // and no errors for empty descriptions
    if (ModelState.IsValid)
    {
        // Save
    }
    return View(model);
}
+3
source share
3 answers

Turns out the checkbox problem was the whole problem. I found a solution to this problem elsewhere in our code, so I used it. It seems to be hacked, but it works.

The idea is that you need to make sure the value of the check box true, not "on". So do this:

<input type="checkbox" id="myCheckbox" value="true" />

Then add the hidden input with the same identifier with your value as falseimmediately after this check box:

<input type="hidden" id="myCheckbox" value="false" />

, . , , myCheckbox=false, , . , . ( , ). , myCheckbox=true.

+8

, , :

Html.CheckBox("FieldName")
+3

, Enum. , , - -, .

, , , , /, / .

In two ways, this can change your view as True / False or, and this is what I did to write my own ModelBinder, which performs the conversion from Yes to True.

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1743043/


All Articles