从我学到的MVC中不能真正提供'开箱即用'的客户端验证。 有第三方选项,但我更喜欢做我自己的事情,所以我用JavaScript编写了整个事情。 若要使用EditorFor复合事项不允许添加像其他帮助方法一样的HTML属性。
我给这家修复是相当复杂的,但我觉得全面的,我希望你觉得它是有帮助我
首先过载的HtmlHelper EditorFor在.net
public static HtmlString EditBlockFor<T, TValue>(this HtmlHelper<T> helper, Expression<System.Func<T, TValue>> prop, bool required)
{
string Block = "";
Block += "<div class='UKWctl UKWEditBox' " +
"data-oldvalue='" + helper.ValueFor(prop) + "' " +
"data-required='" + required.ToString() + ">";
Block += helper.EditorFor(prop);
Block += "</div>";
return new HtmlString(Block);
}
添加新editBlockfor在Razor视图(就像你),但改变形式开始的方法添加一个名称和ID的表单元素,以便您可以识别它以后
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { name = "MyDataForm", id = "MyDataForm" }))
然后,当用户点击保存,从JavaScript运行验证方法
function validate(container) {
var valid = true;
//use jquery to iterate your overloaded editors controls fist and clear any old validation
$(container).find(".UKWctl").each(function (index) { clearValidation($(this)); });
//then itterate Specific validation requirements
$(container).find(".UKWctl[data-required='True']").each(function (index) {
var editobj = getUKWEdit(this);
if (editobj.val() == "") {
valid = false;
//use this Method to actually add the errors to the element
AddValidationError(editobj, 'This field, is required');
//now add the Handlers to the element to show or hide the valdation popup
$(editobj).on('mouseenter', function (evt) { showvalidationContext(editobj, evt); });
$(editobj).on('mouseout', function() { hidevalidationContext(); });
//finally add a new class to the element so that extra styling can be added to indicate an issue
$(editobj).addClass('valerror');
}
});
//return the result so the methods can be used as a bool
return valid;
}
添加验证方法
function AddValidationError(element, error) {
//first check to see if we have a validation attribute using jQuery
var errorList = $(element).attr('data-validationerror');
//If not Create a new Array()
if (!errorList || errorList.length < 1) {
errorList = new Array();
} else {
//if we have, parse the Data from Json
var tmpobj = jQuery.parseJSON(errorList);
//use jquery.Map to convert it to an Array()
errorList = $.map(tmpobj, function (el) { return el; });
}
if ($.inArray(error, errorList) < 0) {
// no point in add the same Error twice (just in case)
errorList.push(error);
}
//then stringyfy the data backl to JSON and add it to a Data attribute on your element using jQuery
$(element).attr('data-validationerror', JSON.stringify(errorList));
}
最后显示和隐藏实际的错误, 为了方便这一点很容易我滑倒在一个小的div元素的_布局。HTML
<div id="ValidataionErrors" title="" style="display:none">
<h3 class="error">Validation Error</h3>
<p>This item contatins a validation Error and Preventing Saving</p>
<p class="validationp"></p>
</div>
显示
var tipdelay;
function showvalidationContext(sender, evt)
{
//return if for what ever reason the validationError is missing
if ($(sender).attr('data-validationerror') == "") return;
//Parse the Error to an Object
var jsonErrors = jQuery.parseJSON($(sender).attr('data-validationerror'));
var errorString = '';
//itterate the Errors from the List and build an 'ErrorString'
for (var i = 0; i <= jsonErrors.length; i++)
{
if (jsonErrors[i]) {
//if we already have some data slip in a line break
if (errorString.length > 0) { errorString += '<br>'; }
errorString += jsonErrors[i];
}
}
//we don't want to trigger the tip immediatly so delay it for just a moment
tipdelay = setTimeout(function() {
//find the p tag tip if the tip element
var validationError = $('#ValidataionErrors').find('.validationp');
//then set the html to the ErrorString
$(validationError).html(errorString);
//finally actually show the tip using jQuery, you can use the evt to find the mouse position
$('#ValidataionErrors').css('top', evt.clientY);
$('#ValidataionErrors').css('left', evt.clientX);
//make sure that the tip appears over everything
$('#ValidataionErrors').css('z-index', '1000');
$('#ValidataionErrors').show();
}, 500);
}
隐藏(它更容易隐藏)
function hidevalidationContext() {
//clear out the tipdelay
clearTimeout(tipdelay);
//use jquery to hide the popup
$('#ValidataionErrors').css('top', '-1000000px');
$('#ValidataionErrors').css('left', '-1000000px');
$('#ValidataionErrors').css('z-index', '-1000');
$('#ValidataionErrors').hide();
}
的使用情况,您可以尝试像
function save()
{
if (validate($("#MyDataForm")))
{
$("#MyDataForm").submit();
}
else {
//all the leg has been done this stage so perhaps do nothing
}
}
这里有些事情是我的CSS用于验证Popup
#ValidataionErrors {
display: block;
height: auto;
width: 300px;
background-color: white;
border: 1px solid black;
position: absolute;
text-align: center;
font-size: 10px;
}
#ValidataionErrors h3 { border: 2px solid red; }
.valerror { box-shadow: 0 0 2px 1px red; }
您是否添加了jQuery不引人注目的验证脚本?我能看到页面中包含的脚本吗? – Giu
删除'for'循环 - 它只需要是'@ Html.EditorFor(m => m.MyCollection)'''EditorFor()'方法接受'IEnumerable'并且足够聪明,集合中的每个项目。但是你的代码没有意义,因为'for'循环是属性'Components'不属性'MyCollection'(是一个错字吗?) –
在任何情况下,你应该为每个属性包含'@ Html.ValidationMessageFor()' 'EditorTemplate'使得用户清楚哪一行有错误(并且摘要应该是@@ Html.ValidationSummary(true,“”,new {@class =“text-danger”})') –