How to ignore model property check?

I am. e How to apply a check on one property of a model while ignoring the others (properties of this model) on if (modelstate.Isvalid) {} ​​??? / "> Model

using System.ComponentModel.DataAnnotations; namespace abc.Model { using System; using System.Collections.Generic; public partial class check_master { public int MCheck_id { get; set; } [Required] public string check_name { get; set; } public string field { get; set; } public Nullable<byte> max_length { get; set; } public int check_id { get; set; } } } 


View

  @using (Html.BeginForm("addCheck", "")) { <input type="hidden" id="from" name="from" value="@ViewBag.from" readonly="readonly" /> <fieldset> <tr> <td> @Html.DropDownList("check_master", "--select checks--") </td> <td> @Html.TextBox("checkName", "") @Html.ValidationMessage("check_name") </td> </tr> </table> </fieldset> <p> <input type="submit" value="Add" /> </p> 

}

+4
source share
3 answers

C [Bind(Exclude = "Property_Name")]

+6
source

Why did you decorate other model properties with validation attributes if they should be ignored? It makes no sense, and it is impossible.

Use view models . Define different presentation models for different situations and based on the presentation model, and the situation will decorate only those properties that need to be checked. Or, better yet, don't decorate anything, use FluentValidation.NET to express your verification requirements in a smooth and very powerful way.

+1
source

This is a somewhat old question, but I do not believe that it was answered properly. Manipulating a binding does not change the manipulation process at all, since the check is performed before / at the same time as the binding. As in the above example, marking the property as excluded will still generate the false property modelstate.isvalid.

The most recommended way to validate is to create dedicated ViewModels, as it takes care of several other issues in the same way that you may or may not know about.

An alternative to ViewModels is to control the modelstate object to get the selection (or exclude) of the property to check as follows:

(there is additional code for deleting magic strings here)

 var modelPropAsString = nameof(yourmodel)+"."+nameof(yourmodel.Id); if (ModelState[modelPropAsString ].Errors.SingleOrDefault() != null) { ModelState[modelPropAsString ].Errors.Clear(); yourmodel.Id = 0; } 

The above excludes the Id property from validation. You can rotate the Id property authentication code if you want.

0
source

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


All Articles