是否有一种简单的方法可以禁用禁用输入字段的模型验证?我的问题是我有一个模型验证的表单我使用jquery来禁用输入并隐藏它并使用Ajax提交表单但是当它被禁用时它仍会对该字段进行模型验证我&#39 ; m使用html 5验证用于客户端和模型验证服务器端。任何帮助将不胜感激。这只是我的代码的一部分,它更大但我只是想知道是否有一种简单的方法来禁用禁用输入字段上的模型验证。不知道你是否能够告诉我如何使用我的代码示例我试图简化它们以获得重点,但我想我可能已经宰了它。我从位置文本框中删除了所需的html 5并禁用了以测试模型验证,该模型验证效果很好但我不希望它在禁用位置文本框时起作用。
[Required(ErrorMessage = "You must enter a location")]
[StringLength(15, ErrorMessage ="Must Be Under 15 Characters")]
public string location_txt_box { get; set; }
[HttpPost]
[ValidateAjax]
public JsonResult AddData(form_model form_data)
{
return Json(form_data);
}
public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0 select new
{
key = x,
errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
<section class="u_select_section">
<center>
<label>
@Html.RadioButtonFor(m => m.user_department_radio_group,"user", htmlAttributes: new{
@id = "u_select"
})
Filling out for myself
</label>
</center>
</section>
<section id="location_display_section" class="location_display_section">
<div id="location_error"></div>
@Html.TextBoxFor(m => m.location_txt_box, htmlAttributes: new{
@id = "dep_loca_id",
@disabled = "disabled",
@placeholder = "Type your Location",
@required = "required"
})
</section>
$('#request_form').on('submit', function (e) {
$.ajax({
type: "POST",
url: "../Home/AddData",
datatype: "json",
data: $("#request_form").serializeArray(),
beforeSend: function () {
$("#progress").show();
},
complete: function () {
$('#progress').hide("fade",2000);
},
success: function (data) {
alert("Success")
},
error: function (data) {
$("#location_error").show();
var response = JSON.parse(data.responseText);
var location_error = response[0].errors[0];
$("#location_error").text("" + location_error + "").css({ "color": "red" });
}
});
e.preventDefault();
});
//disable functions
function disable_function_1(i) {
return $(i).attr("disabled", "disabled");
}
//user and department radio button click functions
$("#u_select").click(function () {
$(dep_loca_id).hide(effect1);//hide the department location text box
disable_function_1(dep_loca_id);//disable the department location text box
});
答案 0 :(得分:0)
您可以使用JSON.parse()
删除特定的字段验证。
ModelState.Remove()