ASP .NET MVC Disable Client Side Validation at Per-Field Level

后端 未结 7 2100
梦毁少年i
梦毁少年i 2020-11-27 02:50

I\'m using ASP .NET MVC 3 with Data Annotations and the jQuery validate plugin.

Is there a way to mark that a certain field (or certain data annotation) should only

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 03:31

    To achieve this goal in the given scenario, we need to make two tweaks.

    Client Side

    To disable client side validation, we need to disable it by force.

    @Html.EditorFor(model => model.Password, new { htmlAttributes = new {  @data_val = "false" , @class = "form-control"} })
    

    Notice the @data_val= “false”. It will disable the validation on this field.

    Server Side (In Action)

    When the model is validated on the post action, ModelState.IsValid will always return false because password is not provided. Here we have to provide the current password to the model and Re-validate the model.

    var userObj = db.Users_Info.Where(a => a.Id == users_Info.Id).FirstOrDefault();
    if (String.IsNullOrEmpty(users_Info.Password))
    {
      users_Info.Password = userObj.Password;
    }
    ModelState.Clear();
    TryValidateModel(users_Info);
    

    Let me explain, first we retrieve current information saved in the database which we are using later to assign to current model if password is not provided. The last two lines actually reset the ModelState to return updated result on ModelState.IsValid.

提交回复
热议问题