0
votes

I've only recently started learning ASP.NET MVC 3 and already faced with such problem. I'm trying to use unobtrusive client validation in my project and there is strange thing about it. Here is code:

The first .cshtml file:

@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>
}

And here is a model class for it:

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

The second .cshtml file:

@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>
}

And a model class for it:

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

and I've used js file from here: 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;
});
});

from the answer about Html.BeginForm().

So, the problem is that when I'm trying to submit the first form, it only alerts "hello" and posting. Server-side validation works correctly and it shoes error messages, but it ignores alert("profit") and whole client validation completely. The second form works correctly and fires client-side validation on submitting. The questions are: where is mistake and how I can force client-side validation work correctly?

1
this may or may not help your issue here, but you want to generally parse your ajax form from $.validator.unobtrusive.parse on load, rather than when it submits.Adam Tuliper - MSFT
So what shall I do? I've already tried @Ajax.BeginForm("Edit", "Tasks", FormMethod.Post, new AjaxOptions { OnBegin = "something" }), it's not working, and I've no idea what else can be done.Vladimir
I have a script somewhere here that helps out with this and a post on here related to this, I'll try to find in just a bit, have some work things going on right now.Adam Tuliper - MSFT
If you do, it'll be very good. Thank you very much for interest to my problem.Vladimir
One more intersting thing is that alert ("profit") on the second page works without any troubles, so the mistake probably somewhere in the first part of code...Vladimir

1 Answers

1
votes

Check out my posting here, I have some code that will help in the ajax updating/validation parsing:

ASP.Net MVC: Can you use Data Annotations / Validation with an AJAX / jQuery call?