English 中文(简体)
ASP. NET MVC 3 违约客户的验证并不总是奏效
原标题:ASP. NET MVC 3 Unobtrusive client validation not always work

我刚刚开始学习伙伴关系。 NET MVC 3已经面临这一问题。 我试图在我的项目中使用不实的客户验证,对此有奇怪之处。 这里是法典:

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

此处为示范类别:

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

a. 示范类:

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

摘自Html.BeginForm()。

因此,问题在于,当我试图提交第一种表格时,它只提醒“hello”和张贴。 服务器方的验证工作正确无误,它散布错误信息,但忽略了警报(“利润”)和整个客户验证。 第二种形式正确操作,并在提交时向客户方开火。 问题是:什么是错的,我如何正确迫使客户方验证工作?

最佳回答

结束我在这里的发言, 我有一部法典,有助于加亚语的更新/验证教区:

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

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签