本系列文章基於ASP.NET MVC beta.本示例Blog系統同步更新的演示站點:http://4mvcblog.qsh.in/
在ASP.NET MVC beta發佈以前,M$就宣佈支持開源的JS框架jQuery,而後ASP.NET MVC beta發佈後,你創建一個ASP.NET MVC beta的項目後,你能夠在項目的scripts目錄下找到ASP.NET AJAX和jQuery的JS。反正我是比較喜歡jQuery的,因此對於M$此舉仍是挺欣慰的。
廢話很少說,咱們使用AJAX來實現發表評論的功能吧。先來看看怎樣使用M$的JS框架來進行異步AJAX請求。
首先,固然是要引入M$的AJAX框架的JS:
scriptsrc="/Content/MicrosoftAjax.js"type="text/javascript"/script
scriptsrc="/Content/MicrosoftMvcAjax.js"type="text/javascript"/script
ASP.NET MVC的框架的Helper方法中提供了對他自身的AJAX的支持,使用的是System.Web.Mvc.Ajax命名空間下面的方法。你能夠這樣寫代碼:
![image](http://static.javashuo.com/static/loading.gif)
或者:
![image](http://static.javashuo.com/static/loading.gif)
在AjaxHelper中並無EndForm方法,你能夠直接寫Html來關閉form,或者你也可使用Html.EndForm();來關閉。好,下面咱們來寫發表評論的AjaxForm:
![image](http://static.javashuo.com/static/loading.gif)
這裏詳細說下AjaxOptions的可選配置的各個屬性的做用。
publicstringConfirm:沒測試,不知道幹嗎用的,知道的說一下.
publicstringHttpMethod:就是指定請求的Http方法,"POST""GET""PUT"等等
publicInsertionModeInsertionMode:返回的內容要更新的目標元素的方式。有三種方式:
Replace:替換目標元素裏面的內容;
InsertBefore:返回內容插入到目標元素的前面;
InsertAfter:返回內容插入到目標元素的後面。
publicstringLoadingElementId:指定在進行異步請求的時候要顯示的提示信息的Loading元素的ID
publicstringOnBegin:在發送異步請求前觸發的JavaScript方法
publicstringOnComplete:在發送異步請求完成後觸發的JavaScript方法
publicstringOnFailure:在發送異步請求失敗的時候觸發的JavaScript方法
publicstringOnSuccess:在發送異步請求成功的時候觸發的JavaScript方法
publicstringUpdateTargetId:指定返回的內容要更新的目標元素的ID
publicstringUrl:請求的URL,不指定則爲form的action的url。
在上面的代碼中,在異步請求成功後會調用名稱爲clearComment的JavaScript方法來清除輸入框的評論內容,而後返回內容會替換掉id爲boxcomments元素裏面的內容。完整的客戶端代碼以下:
![](http://static.javashuo.com/static/loading.gif)
MS Ajax
divclass="entry"
%
Html.RenderPartial("_commentList",ViewData.Model.Comments);
if(BlogSettings.Instance.IsCommentsEnabled){
Ajax.BeginForm("AddComment",new{controller="Home",id=""},newAjaxOptions()
{
HttpMethod="Post",
LoadingElementId="loading",
//OnBegin="commentValidate",
OnSuccess="clearComment",
UpdateTargetId="boxcomments",
InsertionMode=InsertionMode.Replace
},new{id="commentform"});
%
h3id="respond"發表評論/h3
p歡迎留下你的評論,你的支持,是我最大的動力!/p
plabelfor="author"Name(required)/label
inputtype="text"tabindex="1"size="22"value=""id="author"name="author"/
%=Html.ValidationMessage("Author")%/p
plabelfor="email"E-mail(willnotbepublished)(required)/label
inputtype="text"size="22"tabindex="2"value=""id="email"name="email"/
%=Html.ValidationMessage("Email")%/p
plabelfor="url"Website/label
inputtype="text"tabindex="3"size="22"value=""id="Website"name="Website"//p
p%=Html.ValidationMessage("Content")%
textareatabindex="4"rows="10"cols="5"id="commentContent"name="content"/textarea/p
pinputtype="submit"value="SubmitComment"tabindex="5"id="submit"name="submit"/
spanid="loading"style="display:none;"數據處理中
![](http://static.javashuo.com/static/loading.gif)
/span
inputtype="hidden"value="%=ViewData.Model.Id%"id="comment_post_ID"name="comment_post_ID"//p
/form
scripttype="text/javascript"language="javascript"
functionclearComment(a,b,c,d){
$get("commentContent").value="";
}
/script
%}%
/div
以上爲使用M$的AJAX框架來實現AJAX異步請求,下面來看看使用jQuery怎麼作呢。前面說過,我我的比較喜歡jQuery,因此示例的4mvcBlog裏面的將使用jQuery來實現。 首先,咱們用jQuery寫一個用於提交form表單的異步請求的小"插件":
![](http://static.javashuo.com/static/loading.gif)
(function($)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
$.fn.ajaxForm=function(success)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
varform=$(this);
![](http://static.javashuo.com/static/loading.gif)
varbtn=form.find(":submit");
![](http://static.javashuo.com/static/loading.gif)
form.submit(function()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
$.ajax(
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
url:form.attr("action"),
![](http://static.javashuo.com/static/loading.gif)
type:form.attr("method"),
![](http://static.javashuo.com/static/loading.gif)
data:form.serialize(),
![](http://static.javashuo.com/static/loading.gif)
beforeSend:function(xhr)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
btn.attr("disabled",true);
![](http://static.javashuo.com/static/loading.gif)
showLoading();
![](http://static.javashuo.com/static/loading.gif)
},
![](http://static.javashuo.com/static/loading.gif)
success:function(data)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
if(success)
![](http://static.javashuo.com/static/loading.gif)
{success(data);}
![](http://static.javashuo.com/static/loading.gif)
},
![](http://static.javashuo.com/static/loading.gif)
error:function()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
alert("請求出錯,請重試");
![](http://static.javashuo.com/static/loading.gif)
},
![](http://static.javashuo.com/static/loading.gif)
complete:function()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
btn.attr("disabled",false);
![](http://static.javashuo.com/static/loading.gif)
hideLoading();
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
});
![](http://static.javashuo.com/static/loading.gif)
returnfalse;
![](http://static.javashuo.com/static/loading.gif)
});
![](http://static.javashuo.com/static/loading.gif)
};
![](http://static.javashuo.com/static/loading.gif)
functionshowLoading()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
$("#loading").css("display","");
![](http://static.javashuo.com/static/loading.gif)
};
![](http://static.javashuo.com/static/loading.gif)
functionhideLoading()
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
$("#loading").css("display","none");
![](http://static.javashuo.com/static/loading.gif)
};
![](http://static.javashuo.com/static/loading.gif)
})(jQuery);
而後咱們不須要修改原來的通常的form,咱們只須要使用ajaxForm 方法來指定要進行ajax請求的form的id就能夠了:
![](http://static.javashuo.com/static/loading.gif)
formid="commentform"method="post"action="%=Url.Action("AddComment",new{controller="Home",id=""})%"
![](http://static.javashuo.com/static/loading.gif)
h3id="respond"發表評論/h3
![](http://static.javashuo.com/static/loading.gif)
p歡迎留下你的評論,你的支持,是我最大的動力!/p
![](http://static.javashuo.com/static/loading.gif)
plabelfor="author"Name(required)/label
![](http://static.javashuo.com/static/loading.gif)
inputtype="text"tabindex="1"size="22"value=""id="author"name="author"/
![](http://static.javashuo.com/static/loading.gif)
%=Html.ValidationMessage("Author")%/p
![](http://static.javashuo.com/static/loading.gif)
plabelfor="email"E-mail(willnotbepublished)(required)/label
![](http://static.javashuo.com/static/loading.gif)
inputtype="text"size="22"tabindex="2"value=""id="email"name="email"/
![](http://static.javashuo.com/static/loading.gif)
%=Html.ValidationMessage("Email")%/p
![](http://static.javashuo.com/static/loading.gif)
plabelfor="url"Website/label
![](http://static.javashuo.com/static/loading.gif)
inputtype="text"tabindex="3"size="22"value=""id="Website"name="Website"//p
![](http://static.javashuo.com/static/loading.gif)
p%=Html.ValidationMessage("Content")%
![](http://static.javashuo.com/static/loading.gif)
textareatabindex="4"rows="10"cols="5"id="commentContent"name="content"/textarea/p
![](http://static.javashuo.com/static/loading.gif)
pinputtype="submit"value="SubmitComment"tabindex="5"id="submit"name="submit"/
![](http://static.javashuo.com/static/loading.gif)
spanid="loading"style="display:none;"數據處理中
![](http://static.javashuo.com/static/loading.gif)
/span
![](http://static.javashuo.com/static/loading.gif)
inputtype="hidden"value="%=ViewData.Model.Id%"id="comment_post_ID"name="comment_post_ID"//p
![](http://static.javashuo.com/static/loading.gif)
/form
![](http://static.javashuo.com/static/loading.gif)
scripttype="text/javascript"language="javascript"
![](http://static.javashuo.com/static/loading.gif)
//咱們只須要在這裏註冊一下事件就能夠,這就是jQuery和Html乾淨的分離的優雅。
![](http://static.javashuo.com/static/loading.gif)
$("#commentform").ajaxForm(success);
![](http://static.javashuo.com/static/loading.gif)
functionsuccess(data)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
if(data.search(/^\{[\s\S]+\}$/img)-1)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
alert(eval("("+data+")").ErrorMsg.toString());
![](http://static.javashuo.com/static/loading.gif)
}else
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
varc=$(".boxcomments");
![](http://static.javashuo.com/static/loading.gif)
if(c.length=0)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
c=$('divclass="boxcomments"/div');
![](http://static.javashuo.com/static/loading.gif)
c.insertBefore("#commentform");
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
c.html($(data).find(".boxcomments").html());
![](http://static.javashuo.com/static/loading.gif)
$("#commentContent").val("");
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
/script
後臺代碼以下:
![](http://static.javashuo.com/static/loading.gif)
Code
[AcceptVerbs(HttpVerbs.Post|HttpVerbs.Put),CallByAjax(true)] publicActionResultAddCommentByAjax(FormCollectionform) { JsonResultDatajsonData=newJsonResultData(); Commentcomment=newComment(); stringpostId=form["comment_post_ID"]??""; Postpost=Post.GetPost(newGuid(postId)); if(TryUpdateModel(comment,new[]{"Content","Author","Email"})) { if(comment.IsValid) { comment.Id=Guid.NewGuid(); comment.Author=Server.HtmlEncode(comment.Author); //comment.Email=email; comment.Content=Server.HtmlEncode(comment.Content); comment.IP=Request.UserHostAddress; //comment.Country=country; comment.DateCreated=DateTime.Now; comment.Parent=post; comment.IsApproved=!BlogSettings.Instance.EnableCommentsModeration; if(User.Identity.IsAuthenticated) comment.IsApproved=true; stringwebsite=form["Website"]??""; if(website.Trim().Length0) { if(!website.ToLowerInvariant().Contains("://")) website="http://"/+website; Uriurl; if(Uri.TryCreate(website,UriKind.Absolute,outurl)) comment.Website=url; } post.AddComment(comment); SetCommentCookie(comment.Author,comment.Email,website,comment.Country); returnView("_commentList",post.Comments); } else { foreach(stringkeyincomment.BrokenRules.Keys) { //將驗證不經過的信息添加到錯誤信息列表 jsonData.ErrorMsg.Add(comment.BrokenRules[key]); } } } jsonData.IsError=true; returnJson_Net(jsonData);//若是業務邏輯驗證不經過,則返回JSON結果表示的失敗信息 } 對於上面的後臺代碼的[CallByAjax(true)]特性你能夠參考我Asp.net Mvc Preview 5 體驗--實現ActionSelectionAttribute來判斷是否爲AJAX請求而選擇不一樣的Action這一篇文章。 暫時就到這裏吧。Enjoy!具體效果請下載示例代碼運行查看或到演示站點http://4mvcblog.qsh.in/查看。post by Q.Lee.lulu 。 最新的Blog示例程序代碼: 4mvcBlog_10.rar --------------------------------------------------------------------- 更多內容,請關注http://blog.51mvc.com/ 和 http://bbs.51mvc.com/