MVC3 Ajax validation not showing despite model err

2019-07-29 22:35发布

问题:

I have problems getting the validation summary to show in an ajax form.

Web.Config

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

Partial View:

@Html.ValidationSummary()

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "file" }))

Controller:

    [HttpPost]
    public PartialViewResult Move(List<MoveFileResult> moveFileResult)
    {
        if (ModelState.IsValid)
        {    
        }

        // ModelState.AddModelError("err", "eerrr");
  ....

Rendered Html:

<input checked="checked" id="Replace3665" 
     name="MoveFileResult[0].MoveFileAction" 
     type="radio" value="Replace"> Overwrite
<input id="Rename3665" 
     name="MoveFileResult[0].MoveFileAction" 
     type="radio" value="Rename">
Rename to:
<input id="MoveFileResult_0__NewFileName" 
     name="MoveFileResult[0].NewFileName" 
     type="text" value="">
<span class="field-validation-valid" 
   data-valmsg-for="MoveFileResult[0].NewFileName" 
   data-valmsg-replace="true"></span>

Scripts: (UPDATED)

<script src="/Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

They are created like this:

@Html.TextBox(String.Format("MoveFileResult[{0}].NewFileName", i), item.NewFileName)
@Html.ValidationMessage(String.Format("MoveFileResult[{0}].NewFileName", i), item.NewFileName)

ViewModel:

namespace MyProj.MVC.Areas.Admin.ViewModels
{
    public class MoveFilesViewModel
    {

        public List<MoveFileResult> MoveFileResult { get; set; }
    }

    public class MoveFileResult
    {
        [Required]
        public int FileID { get; set; }

        [Required]
        public MoveFileAction MoveFileAction { get; set; }

        //[RequiredIf("MoveFileAction", 2)]
        [Required]
        public string NewFileName { get; set; }    
    }

    public enum MoveFileAction : byte
    {
        Move = 0,
        Replace = 1,
        Rename = 2
    }
}
  1. If I run the ModelState.AddModelError("err", "eerrr"); It will show summary
  2. If I debug, ModelState contains errormessages for each "NewFileName"

Somehow the errormessage doesnt exist in my custom Html-list.

How do I add it to this custom listning of radiobuttons + textbox?

回答1:

you should also add

jquery.validate.js

in the order

<script src="/Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

This is a very nice reference on Unobtrusive Client Validation in ASP.NET MVC 3.