Disable Validation on a single (disabled) @Html.EditorFor

白昼怎懂夜的黑 提交于 2020-02-16 06:55:19

问题


I've read around that the given way of doing this seems to be having different view models (which is a bit overkill imo) for different actions/controllers.

I thought

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

might work but unfortunately not.

Does anyone have any ideas?


回答1:


MVC can be funny when it comes to declaring elements as disabled. I used readonly instead to get around this issue. There just change disabled to readonly as shown below.

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

or an alternative is using an input html element

<input type="text" name="Ingredient.Name" id="Ingredient_Name" readonly="readonly" class="form-control, input-disabled" />

add css class

.input-disabled /* CHANGE STYLING OF READONLY FIELDS */
{
    background-color: #EEEEEE;    
}

then add your class to your html

@Html.EditorFor(model => model.Ingredient.Name, new { htmlAttributes = new { @class = "form-control, input-disabled", readonly= "readonly", data_val = "false"} })

I've created a the following to show you jsfiddle




回答2:


You can make use of .ignore to turn of the client validation on one or more elements.

The nice thing about this is that it is generic an can be applied to multiple elements by just adding the used ignore class.

Add this in your jquery code

$.validator.setDefaults({
    ignore: ".ignore"
});

Apply the ignore class on each element you whish to ignore/disable client side validation.

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



回答3:


All unobtrusive validation (the kind used by ASP.NET MVC) is predicated on finding and parsing data attributes on each object. Those carry all the information that the validation engine needs to run and only elements that have data-val="true" are included.

Any HTML attributes you pass will override any of the default attributes, so the easiest way is to just force data-val="false" and the form element won't be included in the validation engine and none of the other dependent tags will be parsed.

Here's an example from ASP .NET MVC Disable Client Side Validation at Per-Field Level:

@Html.TextBoxFor(m => m.BatchId, new { data_val = "false" })



回答4:


You can disable client side validation in the Razor view before you render field and re-enable. I believe your question has already been answered here



来源:https://stackoverflow.com/questions/34789983/disable-validation-on-a-single-disabled-html-editorfor

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