MVC4 AJAX Unobtrusive

AJAX Function 

$(function () {
$("#album-list img").mouseover(function () {
$(this).animate({ height: '+=25', width: '+=25' })
.animate({ height: '-=25', width: '-=25' });
});
});

jQuery Selectors选择器

$(˝#header˝) id为“header”元素
$(˝.editor-label˝) class为“editor-lable”元素
$(˝div˝) 所有DIV
$(˝#header div˝) 带有ID属性为“header”的DIV
$(˝#header > div˝) 带有ID属性为“header”元素内的DIV
$(˝a:even˝) 找到偶数链接

 

jQuery Events事件

$("a").mouseover(function () {
$(this).addClass("highlight");
}).mouseout(function () {
$(this).removeClass("highlight");
});
$("a").hover(function () {
$(this).toggleClass("highlight");
});

jQuery and Ajax

Unobtrusive JavaScript

<div onclick="javascript:alert('click');">Testing, testing</div>

Using jQuery

<script src="~/Scripts/jquery-1.6.2.js"></script>

Custom Scripts自定义脚本

在MusicScripts.js中添加如下代码

$(function () {
$("#album-list img").mouseover(function () {
$(this).animate({ height: '+=25', width: '+=25' })
.animate({ height: '-=25', width: '-=25' });
});
});

View中引用

<div id="promotion">
</div>
<h3><em>Fresh</em> off the grill</h3>
@section Scripts {
<script src="~/Scripts/MoviesScripts.js")"></script>
}

AJAX HELPERS引入如下代码使用AJAX Helpers

<script src="~Scripts/jquery-1.6.2.min.js")></script>
<script src="~/Scripts/Scripts/jquery.unobtrusive-ajax.min.js")
></script>
@RenderSection("scripts", required:false);

Ajax ActionLinks

在Views/Home/Index.cshtml中加入如下代码

Ajax.ActionLink第一个参数链接名,Action地址,第三个相关参数

复制代码
<div id="dailydeal">
@Ajax.ActionLink("Click here to see today's special!",
"DailyDeal",
new AjaxOptions{
UpdateTargetId="dailydeal",
InsertionMode=InsertionMode.Replace,
HttpMethod="GET"
})
</div>
复制代码

HomeController

复制代码
public ActionResult DailyDeal()
{
var album = GetDailyDeal();
return PartialView("_DailyDeal", album);
}
private Album GetDailyDeal()
{
return storeDB.Albums
.OrderBy(a => a.Price)
.First();
}
复制代码

_DailyDeal.cshtml

复制代码
@model MvcMusicStore.Models.Album
<p>
<img alt="@Model.Title" src="@Model.AlbumArtUrl" />
</p>
<div id="album-details">
<p>
<em>Artist:</em>
@Model.Artist.Name
</p>
<p>
<em>Price:</em>
@String.Format("{0:F}", Model.Price)
</p>
<p class="button">
@Html.ActionLink("Add to cart", "AddToCart",
"ShoppingCart", new { id = Model.AlbumId }, "")
</p>
</div>
复制代码

HTML 5 Attributes Html5属性Ajaxhelper生成如下代码

<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace"
data-ajax-update="#dailydeal" href="/Home/DailyDeal">
Click here to see today&#39;s special!
</a>

JavaScript中执行自定义操作

$(function () {
$("a[data-ajax]=true"). // do something
});

Ajax Forms

复制代码
@using (Ajax.BeginForm("ArtistSearch", "Home",
new AjaxOptions {
InsertionMode=InsertionMode.Replace,
HttpMethod="GET",
OnFailure="searchFailed",
LoadingElementId="ajax-loader",
UpdateTargetId="searchresults",
}))
{
<input type="text" name="q" />
<input type="submit" value="search" />
<img id="ajax-loader"
src="@~/Content/Images/ajax-loader.gif"
style="display:none"/>
}
复制代码

失败时显示错误信息

function searchFailed() {
$("#searchresults").html("Sorry, there was a problem with the search.");
}

执行搜索执行HOME控制器中的ArtistSearch 返回局部视图ArtistSearch

复制代码
public ActionResult ArtistSearch(string q)
{
var artists = GetArtists(q);
return PartialView(artists);
}
private List<Artist> GetArtists(string searchString)
{
return storeDB.Artists
.Where(a => a.Name.Contains(searchString))
.ToList();
}
复制代码

ArtistSearch.cshtml

复制代码
@model IEnumerable<MvcMusicStore.Models.Artist>
<div id="searchresults">
<ul>
@foreach (var item in Model) {
<li>@item.Name</li>
}
</ul>
</div>
复制代码

CLIENT VALIDATION客户端验证

复制代码
[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
public string Title { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
复制代码

jQuery Validation

<script src="~/Scripts/jquery.validate.min.js")
></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js")
></script>

启用AJAX验证在 WEB.CONFIG中设置如下内容

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

VIEW中验证

复制代码
<p>
@Html.LabelFor(model => model.Title)
@Html.TextBoxFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</p>
<p>
@Html.LabelFor(model => model.Price)
@Html.TextBoxFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</p>
复制代码

解析后如下

<input
data-val="true"
data-val-length="The field Title must be a string with a maximum length of 160."
data-val-length-max="160" data-val-required="An Album Title is required"
id="Title" name="Title" type="text" value="Greatest Hits" />

客户端验证代码 

复制代码
  public class MaxWordsAttribute : ValidationAttribute, 
                                     IClientValidatable
    {
        public MaxWordsAttribute(int wordCount)
            :base("Too many words in {0}")
        {
            WordCount = wordCount;           
        }

        public int WordCount { get; set; }

        protected override ValidationResult IsValid(
            object value, 
            ValidationContext validationContext)
        {
            if (value != null)
            {
                var wordCount = value.ToString().Split(' ').Length;
                if (wordCount > WordCount)
                {
                    return new ValidationResult(
                        FormatErrorMessage(validationContext.DisplayName)
                    );
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("wordcount", WordCount);
            rule.ValidationType = "maxwords";
            yield return rule;
        }
    }
复制代码

MaxWordsScript.js

复制代码
/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

if ($.validator && $.validator.unobtrusive) {

    $.validator.unobtrusive.adapters.addSingleVal("maxwords", "wordcount");

    $.validator.addMethod("maxwords", function (value, element, maxwords) {
        if (value) {
            if (value.split(' ').length > maxwords) {
                return false;
            }
        }
        return true;
    });

}
复制代码
posted @ 2013-04-16 10:08  风雪七月花溅墨  阅读(998)  评论(0编辑  收藏  举报