【发布时间】:2017-06-18 02:34:16
【问题描述】:
是否有一种简单的方法可以在禁用的输入字段上禁用模型验证?我的问题是我有一个带有模型验证的表单我正在使用 jquery 禁用输入并隐藏它并使用 Ajax 提交表单但是当它被禁用时它仍然对该字段进行模型验证我正在为客户端使用 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>
jquery 的一部分
$('#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();
});
用于隐藏和禁用的 Jquery
//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
});
【问题讨论】:
-
发布一些示例代码
标签: jquery asp.net-mvc