简体   繁体   中英

Disable Required Validation Specific Field in the View ASP.NET MVC 4

if someone could give me some hint I would appreciate.

I'm searching for a while, and I even found a post I thought it would solve my problem, but it didn't.

Disable Required validation attribute under certain circumstances

Basically I have a simple User.cs model where I have username, FirstName , LastName and SignupDate

All have the required annotation and I would like to solve this without erasing the Required tag.

After I generate the view, I erase in the view the html code for the SignupDate :

 <div class="editor-label">
        @Html.LabelFor(model => model.SignupDate)
 </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.SignupDate)
        @Html.ValidationMessageFor(model => model.SignupDate)
 </div>

When I click submit it does not work.

Also if I do the suggested in the other post

<div class="editor-label">
        @Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
       @Html.TexBoxFor(model => model.SignupDate, new { data_val = false })
</div>

If I leave it as blank also does not work..

Any suggestions? Thanks!!

You can disable client validations on the view and remove the errors on the modelstate for those entities you don't want to validate the value.

In my case I wanted to change a Password only if the user typed one. Using Html.HiddenFor was not a good approach due to sends the password to the client every time, and password shouldn't be sent.

What I did was to disable the client validations on the view

@model MyProject.Models.ExistingModelWithRequiredFields

@{
    ViewBag.Title = "Edit";
    Html.EnableClientValidation(false);
}

That allows me to submit the form even with empty values. Please note that all client validations are ignored , however server validations still run , so you need to clear those you don't need to be executed. In order to do this, go to the action in the controller and remove the errors for each property you need to

public ActionResult Edit(ExistingModelWithRequiredFields updatedModel)
{
    var valueToClean = ModelState["RequiredPropertyName"];
    valueToClean.Errors.Clear(); 
    if(ModelState.IsValid)
    {
        ...
        //Optionally you could run validations again 
        if(TryValidateModel(updatedModel)
        {
            ...
        }
        ...
    }
    ...
}

我认为这应该解决它,假设model.SignupDate持有一个值:

<%: Html.HiddenFor(model => model.SignupDate) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM