Asp.net MVC 3 中 Unobtrusive javascript 与Ajax

   
前边的稿子咱们介绍了jquery.validate.unobtrusive
脚本实现Asp.net
MVC3表单验证。这里我们介绍应用jquery.unobtrusive-ajax.js实现的ajax操作.首先保证的是在Web.config中配置节:

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

地点的代码,大家利用了AjaxOptions,这样帮大家指定要立异UpdateTargetId,调用成功要实践的Js
function,以及失利未来推行Js function.
这里当大家的ajax调用成功后我们回到一个叫”_result.cshtml”的partialView,内容是这么的:

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

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

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

下边是重点用示演的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

相关文章