有沒有簡單的方法來禁用模型驗證禁用輸入字段?我的問題是我有一個表單與模型驗證我正在使用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
});
後一些示例代碼 –