在foreach

时间:2015-07-21 22:23:31

标签: javascript jquery asp.net-mvc validation model-view-controller

所以我有一个具有以下结构的视图(这不是实际代码,而是摘要):

@using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
  @Html.ValidationSummary("", new { @class = "text-danger" })
  <table>
    <thead>
      <tr>
        <th>Column1</th>
        <th>Column2</th>
      </tr>
    </thead>
    <tbody id="myTableBody">
      @for (int i = 0; i < Model.Components.Count; i++)
      {
        @Html.EditorFor(m => m.MyCollection[i])
      }
    </tbody>
    <tfoot>
      <tr>
        <td>
          <button id="btnAddRow" type="button">MyButton</button>
        </td>
      </tr>
    </tfoot>
  </table>

  <input type="button" id="btnSubmit" />
}

@section scripts {
  @Scripts.Render("~/Scripts/MyJs.js")
}

EditorFor正在渲染标记,表示绑定到MyCollection中属性的行。以下是编辑器模板外观的示例摘录:

&#13;
&#13;
@model MyProject.Models.MyCollectionClass

<tr>
  <td>
    @Html.TextBoxFor(m => m.Name)
  </td>
  <td>
    @Html.DropDownListFor(m => m.Type, Model.AvailableTypes)
  </td>
</tr>
&#13;
&#13;
&#13;

基本上,我的问题是客户端验证不会像编辑模板内部的元素那样触发。有人能指出我可能出错的地方正确的方向。

另请注意,我的web.config中设置了以下内容。

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

并且MyCollectionClass对应强制执行的属性具有正确的[Require]注释。需要注意的另一件事是检查

if(ModelState.IsValid)
{
}

如果必填字段不对,则按预期返回false。问题是我想要客户端验证而不是服务器端。我的其他页面之一是实现jQuery验证,但不包含此场景所做的所有嵌套,因此它可以正常工作。

提前致谢。

1 个答案:

答案 0 :(得分:2)

据我所知,MVC并不能真正提供开箱即用的功能。客户端验证。 有第三方选项,但我更喜欢做自己的事情所以我用JavaScript处理整个事情。 使用EditorFor复合问题不允许像其他Helper方法一样添加html属性。

我对此的修复相当复杂,但我觉得很全面,我希望你发现它像我一样有用

首先在.Net中重载HtmlHelper EditorFor

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(就像你一样),但改变Begin Form方法,将一个Name和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元素放入_Layout.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
    }
}

这是用于验证Popup的My Css

#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; }