2

类似的问题已经被(Custom ValidationSummary template Asp.net MVC 3)要求但无论答案满足额外的要求,我也有,这是该解决方案不破客户端 - 方验证。自定义的ValidationSummary模板(即不破坏客户端验证)

因此,没有人知道一种方式来获得这样的功能:

@if (!ViewData.ModelState.IsValid) 
{ 
    <div class="form-errors"> 
     <p>Please have another look at the fields highlighted below</p> 
     @Html.ValidationSummary() 
    </div> 
} 

与客户端验证工作?

这正是我在客户端验证关闭时所需要的,即如果模型有效,则排除整个div,如果存在任何错误,则显示它。但是,条件意味着当评估为false时首先呈现表单时,整个部分不会呈现,因此jquery.validate找不到插入验证摘要的任何位置。

任何想法?

回答

3

帮手:

public static MvcHtmlString MyValidationSummary(this HtmlHelper helper, bool excludePropertyErrors = false) 
    { 
     string html = ""; 

     html += helper.ViewData.ModelState.IsValid ? "<div class='form-errors' style='display:none;'>" : "<div class='form-errors'>"; 

     html += "<p>Please have another look at the fields highlighted below</p>"; 
     html += helper.ValidationSummary(excludePropertyErrors); 
     html += "</div>"; 

     return new MvcHtmlString(html); 
    } 

查看:

@using (Html.BeginForm("Index", "Home",FormMethod.Post, new {id="myform"})) 
{ 
    @Html.MyValidationSummary() 
    ... 
    <input type="button" id="submitbutton" value="Submit" /> 
} 

JS:

$("#submitbutton").click(function() { 
    $("#myform").validate(); 

    if (!$("#myform").valid()) { 
     $("#myform .form-errors").show(); 
    } 
    else { 
     $("#myform").submit(); 
    } 
}); 

更新:

如果你想要去的部分鉴于

共享/ _MyValidationSummary.cshtml

@if (!ViewData.ModelState.IsValid) 
{ 
    <div class="form-errors"> 
     <p>Please have another look at the fields highlighted below</p> 
     @Html.ValidationSummary() 
    </div> 
} 
else 
{ 
    <div class="form-errors" style="display:none;"> 
     <p>Please have another look at the fields highlighted below</p> 
     @Html.ValidationSummary() 
    </div> 
} 

查看:

@using (Html.BeginForm("Index", "Home",FormMethod.Post, new {id="myform"})) 
{ 
    @Html.Partial("_MyValidationSummary") 
    ... 
    <input type="button" id="submitbutton" value="Submit" /> 
} 
+0

这是相当不错的办法,sormii。我想这将是微不足道的,因为我有一个真正的不喜欢埋在像这样的字符串中的html,因此将部分视图的html助手切换出来。 – SimonF

+0

我明白你的观点,无论如何都更新了局部视图方法的答案。 –

+0

不错的一个!我会给你打勾,直到有人设法找到更优雅的解决方案;) – SimonF

相关问题