启用/禁用mvc 2中某些隐藏文本框的验证

时间:2011-08-08 10:56:42

标签: asp.net-mvc validation asp.net-mvc-2 client-side-validation

我有[隐藏]和[取消隐藏]输入按钮,隐藏按钮显示一些文本框,隐藏按钮隐藏一些文本框,我想要做的是只启用那些可见和禁用的框验证验证客户端不可见的方框。目前我在所有方框上进行验证,帖子操作也验证了通过jquery隐藏的文本框,下面是代码:

查看

<script type="text/javascript">

$(document).ready(function () {
    var $startdates = $('#startDates');
    var $endDates = $('#endDates');
    var $showEvents = $('#showEvents');
    $startdates.hide();
    $endDates.hide();
    $showEvents.hide();

    $('#all').click(function () {
        $startdates.show();
        $endDates.show();
        $('#showEvents').show();
        $('#eventdids').hide();
        $(this).hide();
        return false;

    });

    $('#showEvents').click(function () {
        $startdates.hide();
        $endDates.hide();

        $('#eventdids').show();
        $('#all').show();
        $(this).hide();
        return false;

    });
});
 </script>
<tr id="startDates">
        <td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.StartDate) %>
        </div>
        </td>
        <td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.StartDate) %>
            <%: Html.ValidationMessageFor(model => model.StartDate) %>
        </div>
        </td>
        </tr>

        <tr id="endDates">
        <td>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.EndDate) %>
        </div>
        </td>
        <td>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.EndDate) %>
            <%: Html.ValidationMessageFor(model => model.EndDate) %>
        </div>
        </td>
        </tr>


        <tr id="eventdids">
        <td>
        <label>Events</label>
        </td>
        <td>
         <% foreach (var item in (SelectList)ViewData["events"]) { %>
                 <input type="checkbox" name="Name" value="<%=item.Value %>" />
                  <label for="<%=item.Value%>"><%=item.Text%></label>
                  <br />

        <% } %> 

        </td>
        <td><input type="button" name="Select" id="all" style="width:auto" value="Hide" /></td>


        </tr>

        </table>
      <input type="button" name="show" id="showEvents" style="width:auto" value="Show" />

        <p>
            <input type="submit" value="Create" />
        </p>

控制器:

 [HttpPost]
    public ActionResult Create(FormCollection collection, int[] Name)
    {

        IVoucherRepository voucherResp = new VoucherRepository();
            string empty = "";
            if (Name != null)
            {
                for (int i = 0; i < Name.Length; i++)
                {
                    empty += Convert.ToString(Name[i]) + ",";
                }

            }
            else
            {
                ModelState.AddModelError("Venue", "Required");

            }
            if (Convert.ToBoolean(collection["pound"].ToLower().StartsWith("false")) && Convert.ToBoolean(collection["percentage"].ToLower().StartsWith("false")))
            {
                ModelState.AddModelError("","Please Select £ or % for discount");
            }
            if (collection["UsageQtyAvailable"] == null) { ModelState.AddModelError("UsageQtyLeft", "Required "); }

            Voucher voucher = new Voucher();
            if (TryUpdateModel(voucher) && ModelState.IsValid)
            {
                voucher.Status = true;
                voucher.DateAdded = DateTime.Now;
                voucher.DateModified = DateTime.Now;
                if(Convert.ToBoolean(collection["pound"].ToLower().StartsWith("true")))
                {
                voucher.DiscountType = 1;
                }
                else if (Convert.ToBoolean(collection["percentage"].ToLower().StartsWith("true")))
                {
                    voucher.DiscountType = 2;
                }
                voucher.VoucherType = 1; //Discount Code
                voucher.UsageQtyLeft = Convert.ToInt32(collection["UsageQtyAvailable"]);
                string removeComma = empty.Remove(empty.Length - 1,1);
                voucher.EventIDs = removeComma;
                voucherResp.Add(voucher);
                voucherResp.Save();
                return RedirectToAction("Index");
            }

            ITrackdayRepository trackdayResp = new TrackdayRepository();
            IQueryable<Object> getAllEvents = trackdayResp.GetEventsSelectlist();

            ViewData["events"] = new SelectList(getAllEvents.ToList(), "EventID", "Name");
            return View();

    }

2 个答案:

答案 0 :(得分:2)

您可以通过jquery检查文本框是否隐藏,并在提交表单之前将其删除,然后仅验证提交的表单元素。

...
<input type="submit" value="Create" id="create" />
...

$("#create").click(function() { 
        $('#eventdids:hidden').remove();
        $('#all:hidden').remove();
    $("#formID").submit(); 
});

答案 1 :(得分:2)

您还可以使用此小插件删除表单中所有隐藏字段的验证:

(function($) {
    $.fn.refreshValidator = function() {
        var form = this;

        // Get validation settings object
        var settings = form.validate().settings;

        // Remove validation for hidden elements
        $(this).find(':hidden').each(function(){
            var id = $(this).attr('id');
            delete settings.rules[id];
            delete settings.messages[id];
        });
    };
})(jQuery);

您可以这样称呼它:

$('#yourFormId').refreshValidator();

这种方式更可重复使用。