我正在努力弄清爲什麼我的劍道驗證無效......但首先讓我備份。劍道驗證器未針對MVC局部視圖進行射擊
我有一個頁面和一個按鈕的mvc 5網絡應用程序。點擊按鈕,一個模式kendoWindow顯示一個局部視圖來捕捉用戶的兩個輸入。我有我認爲的傳統MVC驗證過程。
[Validator(typeof(MyModelValidator))]
public partial class MyModel
{ ... }
但是它會發布到一個無效的模型控制器(我是測試無效提交)狀態,則立即拋出一個錯誤,因爲它不能完全與更新,它只是附帶的「莫代爾」局部視圖處理從驗證檢查必填字段消息。
因此,經過研究和閱讀,我確定了...也許不正確......使用kendo驗證器是此場景的唯一選項。
所以我着手實施以下Telerik文檔。
在模型中,我有5個屬性,但我只裝飾了一個圖形,在完成它們之前,我會先對它進行散列處理。所以我評論了我的MVC驗證,並在我的模型中加入這樣的:
[Required]
[Display(Name = "Financial Named")]
public virtual string FinancialInstitutionName { get; set; }
在CSHTML:
....snip.....
@Html.LabelFor(model => model.FinancialInstitutionName):
</td>
<td>
@Html.EditorFor(model => model.FinancialInstitutionName)
@Html.ValidationMessageFor(model => model.FinancialInstitutionName)
</td>
.....and further down.....
$(function()
{
$("#formCreateEditFinancier").kendoValidator();
});
而且控制器:
public ActionResult CreateEditFinancialInstitute(int financierId, int isChanging)
{
var model = new FinancierModel();
return
PartialView("~/.../CreateEditFinancialInstitute.cshtml", model);
}
現在上面是什麼產生/在部分視圖在模態對話框中呈現時被消耗。
下面是什麼是所用的「父母」頁面與啓動模式對話框按鈕...
var window = $("#window").kendoWindow(
{
modal: true,
width: "600px",
height: "400px",
title: "Fill in the blanks eh...",
actions: ["Close"],
content: {
url: "@Html.Raw(Url.Action("CreateEditFinancialInstitute", "FinancingPayment"))",
data: { financierId: financierid, isChanging: ischanging }
}
});
window.data('kendoWindow').center();
最後這裏是產生的模態窗口的HTML。
<form id="formCreateEditFinancier" action="/FinancingPayment/CreateEditFinancialInstitute" method="post" novalidate="novalidate" data-role="validator">
這是什麼novalidate屬性呢?我讀了這個,它似乎是HTML 5注入的東西...我當然沒有指定它。所以我添加了一條json行來擺脫它。
$("#formCreateEditFinancier").removeAttr("novalidate");
的HTML渲染沒有它,但我仍然沒有客戶端驗證????
所以最後,我想要的是某種形式的驗證....我的意思是我可以使用一些真正的老學校json檢查字段長度等,但希望能夠使用更新的方法。
編輯
基於iceburg的建議我修改我的模態窗體窗口javascript來此:
var validator = $("#formCreateEditFinancier").kendoValidator().data("kendoValidator");
$("form").submit(function (event)
{
event.preventDefault();
if (validator.validate())
{
alert('gtg');
}
else
{
alert('fail');
}
});
現在,當我裝的形式和點擊提交(無場完成)它顯示警報GTG ....等待它應該失敗!
現在查看HTML是否呈現驗證裝飾。
<input name="FinancialInstitutionName" class="text-box single-line" id="FinancialInstitutionName" type="text" value="" data-val="true" data-val-required="The Financial Named field is required.">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="FinancialInstitutionName"></span>
它出現在「必需的」屬性沒有得到set.If我編輯F12開發工具的HTML添加所需的屬性然後點擊提交我的驗證工作,因爲它應該......如此看來問題就出以及我的模型裝飾如何呈現。
解決
因此,與iceburg的指導下,我發現我的DataAnnotations沒有正常顯示....實際上都是他們,但我錯過了驗證js文件爲解釋在這裏:
Data annotations not working in view model