Asp.net MVC 3 中 Unobtrusive javascript 与Ajax

发布时间:2018-09-24  栏目:法律  评论:0 Comments

   
前面的篇章我们介绍了jquery.validate.unobtrusive
脚本实现Asp.net
MVC3表单验证。这里我们介绍以jquery.unobtrusive-ajax.js实现的ajax操作.首先保证的凡在Web.config中配置节:

       
有时我们得防范退格键的网页后退,一般情况下最为好永不这样用,因为对UX体验不好。
下面是Js片段在IE9,Firebox 10.0.2 中测试过 : 

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

我们有一个_register.cshtml的PartialView : 

 

<script type="text/javascript">
    function ReloadForm(xhr) {
        $('#formcontent').html(xhr.responseText);
    }

    function ClearValidationErrors() {
        $('.validation-summary-errors').html('');
        $('.input-validation-error').removeClass('input-validation-error');
        $('.field-validation-error').remove();
    }
</script>

@using (Ajax.BeginForm("IndexPost", "Home", Model, new AjaxOptions { UpdateTargetId = "formresults", HttpMethod = "Post", OnSuccess = "ClearValidationErrors", OnFailure = "ReloadForm(xhr)" }))
{
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Email)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Email)
                @Html.ValidationMessageFor(m => m.Email)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.ConfirmPassword)
            </div>

            <p>
                <input type="submit" value="Register" />
            </p>
        </fieldset>
    </div>
}
$(document).keydown(function (e) {
    var doPrevent;
    if (e.keyCode == 8) {
        var d = e.srcElement || e.target;
        if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else
            doPrevent = true;
    }
    else
        doPrevent = false;

    if (doPrevent)
        e.preventDefault();
}); 

上面的代码,我们以了AjaxOptions,这样帮我们指定要更新UpdateTargetId,调用成功而实施的Js
function,以及失败以后推行Js function.
这里当我们的ajax调用成功后我们回到一个给”_result.cshtml”的partialView,内容是如此的:

 

<h2>Thanks for registering!</h2>
<p>You have successfully registered</p>

       
关于怎样规定Backspace键的代码可以通过这里.

在_Layout.cshtml中定义一个header节:

        希望对你Web开发有帮。
       
        您或许感兴趣之稿子:
     
       
用Jquery,CSS3实现像GooglePlus那样的圈效果

@if(IsSectionDefined(“Header”))
{
    @RenderSection(“Header”)
}

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
正文版权归作者和博客园共有,欢迎转载,但未经作者同意要保留这个段子声明,且当篇章页面明显位置被闹原文连接,否则保留追究法律责任的权利。
拖欠篇吧同时披露在自己之单独博客中-Petter Liu
Blog。

下是必不可缺用示演的Index.cshtml的内容.
你可见见一个id叫formresults,AJAX调用成功后将会晤更新她:

 

@model AjaxTest.Models.RegisterModel
@{
    ViewBag.Title = "Home Page";
}
@section Header
{
    <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/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
}
<h2>@ViewBag.Message</h2>
<div id="formcontent">
    @{ Html.RenderPartial("_register", Model); }
</div>
<div id="formresults"></div>


Controller的代码是这样的,IndexPost Action就是我们Ajax的Post 目标.

 

public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    return View(new AjaxTest.Models.RegisterModel());
}

[HttpPost]
public ActionResult IndexPost(AjaxTest.Models.RegisterModel model)
{
    if (ModelState.IsValid)
    {
        return PartialView("_results");
    }

    HttpContext.Response.StatusCode = 500;
    HttpContext.Response.Clear();
    return PartialView("_register", model);
}

Model是这样的:

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

当View执行时我们来看这样的HTML,你得看来Form 标签加上了
data-ajax,data-ajax-method等特色, 而input上data-* 用来开证明:

<form action="/Home/IndexPost" data-ajax="true" data-ajax-failure="ReloadForm(xhr)" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="ClearValidationErrors" data-ajax-update="#formresults" id="form0" method="post">    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                <label for="UserName">User name</label>
            </div>
            <div class="editor-field">
                <input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />

            </div>

            <div class="editor-label">
                <label for="Email">Email address</label>
            </div>
            <div class="editor-field">
                <input data-val="true" data-val-required="The Email address field is required." id="Email" name="Email" type="text" value="" />

            </div>

            <div class="editor-label">
                <label for="Password">Password</label>
            </div>
            <div class="editor-field">
                <input data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-length-max="100" data-val-length-min="6" data-val-required="The Password field is required." id="Password" name="Password" type="password" />

            </div>

            <div class="editor-label">
                <label for="ConfirmPassword">Confirm password</label>
            </div>
            <div class="editor-field">
                <input data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="ConfirmPassword" name="ConfirmPassword" type="password" />

            </div>

            <p>
                <input type="submit" value="Register" />
            </p>
        </fieldset>
    </div>
</form>

 

而生趣味可以查Asp.net MVC 3
RTM的源代码,下面是来AjaxOptions类ToUnobtrusiveHtmlAttributes方法,你可以看出data-*和表单中变化的同。

public IDictionary<string, object> ToUnobtrusiveHtmlAttributes() {
    var result = new Dictionary<string, object> {
        { "data-ajax", "true" },
    };

    AddToDictionaryIfSpecified(result, "data-ajax-url", Url);
    AddToDictionaryIfSpecified(result, "data-ajax-method", HttpMethod);
    AddToDictionaryIfSpecified(result, "data-ajax-confirm", Confirm);

    AddToDictionaryIfSpecified(result, "data-ajax-begin", OnBegin);
    AddToDictionaryIfSpecified(result, "data-ajax-complete", OnComplete);
    AddToDictionaryIfSpecified(result, "data-ajax-failure", OnFailure);
    AddToDictionaryIfSpecified(result, "data-ajax-success", OnSuccess);

    if (!String.IsNullOrWhiteSpace(LoadingElementId)) {
        result.Add("data-ajax-loading", "#" + LoadingElementId);

        if (LoadingElementDuration > 0) {
            result.Add("data-ajax-loading-duration", LoadingElementDuration);
        }
    }

    if (!String.IsNullOrWhiteSpace(UpdateTargetId)) {
        result.Add("data-ajax-update", "#" + UpdateTargetId);
        result.Add("data-ajax-mode", InsertionModeUnobtrusive);
    }

    return result;
}

望对您支出辅助,您或许感兴趣的稿子:

HTML5中custom data-*特色与asp.net mvc 3
表单验证 
Html
5遇于定义data-*特性

作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意要保留这个段子声明,且在文章页面明显位置让闹原文连接,否则保留追究法律责任的权。
该文章吧又揭晓以我的独自博客中-Petter Liu
Blog。

留下评论