0

我最近才开始学习 ASP.NET MVC 3 并且已经面临这样的问题。我正在尝试在我的项目中使用不显眼的客户端验证,这很奇怪。这是代码:

第一个 .cshtml 文件:

@model Task_2.Models.Worker
@{
  ViewBag.Title = "Edit:";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit:</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/CausesValidation/Validation.js")"
type="text/javascript"></script>

@using (Html.BeginForm())
{
 @Html.ValidationSummary(true)
<fieldset>
    <legend>Worker</legend>

    @Html.HiddenFor(model => model.worker_id)

    <div class="editor-label">
        @Html.LabelFor(model => model.Surname)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Surname)
        @Html.ValidationMessageFor(model => model.Surname)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Second_Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Second_Name)
        @Html.ValidationMessageFor(model => model.Second_Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Profession)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.Profession,
              (IEnumerable<SelectListItem>)ViewData["ProfessionList"])
        @Html.ValidationMessageFor(model => model.Profession)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Age)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Age)
        @Html.ValidationMessageFor(model => model.Age)
    </div>
     <div class = "display-label">Projects:</div>
    <div class="editor-label">
        <table>
            @foreach (var item in (IEnumerable<string>)ViewData["WorkerTasks"])
            {
                 <tr>
                 <td>@Html.DisplayFor(modelitem => item)</td>
                 </tr>   
            }
        </table>
    </div>

    <div>
        @Html.ActionLink("EditTasks", "EditTasks", new { id = Model.worker_id })
    </div>
    <p>
        <input type="submit" value="Save"  name="Button_Edit_Worker"/>
    </p>
</fieldset>
}

这是一个模型类:

public partial class Worker
{
    public Worker()
    {
        this.Tasks = new HashSet<Task>();
    }
    [Key]
    public System.Guid worker_id { get; set; }

    [RegularExpression(@"[A-ZА-ЯЁ][A-ZА-ЯЁa-zа-яё .()-]*$", 
          ErrorMessage = "Ошибка! Некорректный ввод!")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public string Surname { get; set; }


    [RegularExpression(@"[A-ZА-Я][A-ZА-ЯЁЁa-zа-яё .()-]*$",
    ErrorMessage = "Ошибка! Некорректный ввод!")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public string Name { get; set; }


    [RegularExpression(@"[A-ZА-ЯЁ][A-ZА-ЯЁa-zа-яё .()-]*$", 
      ErrorMessage = "Ошибка! Некорректный ввод!")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public string Second_Name { get; set; }

    public string Profession { get; set; }



    [RegularExpression(@"[0-9]*$", 
      ErrorMessage = "Ошибка! Введите корректное число")]  
    [Range(16,100,ErrorMessage = "Ошибка! Введите число от 16 до 100")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public int Age { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }
}    
}

第二个 .cshtml 文件:

@model Task_2.Models.Task

@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit:</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
 type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/CausesValidation/Validation.js")"
type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Задание:</legend>

        @Html.HiddenFor(model => model.task_id)
    <div class="editor-label">
        @Html.LabelFor(model => model.Tusk_Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Task_Name)
        @Html.ValidationMessageFor(model => model.Tusk_Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Date)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Date)
        @Html.ValidationMessageFor(model => model.Date)
    </div>
    @ViewBag.message


    @if (ViewBag.source != "null")
    {
        <div>
          @Html.ActionLink("Back to task list of the current worker", 
          "EditTasks","Worker", new { id = new Guid(ViewBag.source) }, new { })
        </div>
    }

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

</fieldset>
}

以及它的模型类:

public partial class Task
{
    public Task()
    {
        this.Workers = new HashSet<Workers>();
    }
    [Key]
    public int task_id { get; set; }

    [RegularExpression(@"[A-ZА-ЯЁa-zа-яЁ0-9 .:()-]*$", 
     ErrorMessage = "Ошибка! Некорректный ввод!")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public string Tusk_Name { get; set; }

    [DataType(DataType.Date)]//, ErrorMessage = "Ошибка! Некорректный ввод!")]
    [Required(ErrorMessage = "Ошибка! Введите данные!")]
    public System.DateTime Date { get; set; }

    public virtual ICollection<Worker> Workers { get; set; }
}

我使用了这里的 js 文件: MVC3 Client Side Validation not working with an Ajax.BeginForm form

alert("hello");
$(function () {
$('form').submit(function () {

    $.validator.unobtrusive.parse($('form'));  //added
    alert("profit");
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                $('#result').html(result);
            }
        });
    }
    return false;
});
});

从关于 Html.BeginForm() 的答案。

所以,问题是当我尝试提交第一个表单时,它只会提醒“你好”并发布。服务器端验证正常工作,它提供错误消息,但它完全忽略了 alert("profit") 和整个客户端验证。第二种形式正常工作并在提交时触发客户端验证。问题是:错误在哪里以及如何强制客户端验证正常工作?

4

1 回答 1

1

在这里查看我的帖子,我有一些有助于 ajax 更新/验证解析的代码:

ASP.Net MVC:您可以通过 AJAX/jQuery 调用使用数据注释/验证吗?

于 2012-05-10T14:06:01.833 回答