[轉]ASP.NET MVC 入門11、使用AJAX

來源:互聯網
上載者:User

標籤:style   blog   http   io   os   使用   java   ar   for   

在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:

<script src="/Content/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Content/MicrosoftMvcAjax.js" type="text/javascript"></script> 

 

ASP.NET MVC的架構的Helper方法中提供了對他自身的AJAX的支援,使用的是System.Web.Mvc.Ajax命名空間下面的方法。你可以這樣寫代碼:

或者:

在AjaxHelper中並沒有EndForm方法,你可以直接寫Html來關閉form,或者你也可以使用Html.EndForm();來關閉。好,下面我們來寫發表評論的AjaxForm:

這裡詳細說下AjaxOptions的可選配置的各個屬性的作用。

public string Confirm :沒測試,不知道幹嘛用的,知道的說一下.
public string HttpMethod :就是指定請求的Http方法,"POST" "GET" "PUT" 等等
public InsertionMode InsertionMode :返回的內容要更新的目標元素的方式。有三種方式:
    Replace :替換目標元素裡面的內容;
    InsertBefore :返回內容插入到目標元素的前面;
    InsertAfter:返回內容插入到目標元素的後面。

public string LoadingElementId :指定在進行非同步請求的時候要顯示的提示資訊的Loading元素的ID
public string OnBegin :在發送非同步請求前觸發的JavaScript方法
public string OnComplete :在發送非同步請求完成後觸發的JavaScript方法
public string OnFailure :在發送非同步請求失敗的時候觸發的JavaScript方法
public string OnSuccess :在發送非同步請求成功的時候觸發的JavaScript方法
public string UpdateTargetId :指定返回的內容要更新的目標元素的ID
public string Url :請求的URL,不指定則為form的action的url。

 

在上面的代碼中,在非同步請求成功後會調用名稱為clearComment的JavaScript方法來清除輸入框的評論內容,然後返回內容會替換掉id為boxcomments元素裡面的內容。完整的用戶端代碼如下:


<div class="entry">
<% 
    Html.RenderPartial("_commentList", ViewData.Model.Comments);
    if (BlogSettings.Instance.IsCommentsEnabled){ 

   Ajax.BeginForm("AddComment", new { controller = "Home", id = "" }, new AjaxOptions()
   {
       HttpMethod = "Post",
       LoadingElementId = "loading",
       //OnBegin = "commentValidate",
       OnSuccess = "clearComment",
       UpdateTargetId = "boxcomments",
       InsertionMode = InsertionMode.Replace
   }, new { id = "commentform" }); 
%> 

    <h3 id="respond">發表評論</h3>
    <p>歡迎留下你的評論,你的支援,是我最大的動力!</p>
    <p><label for="author">Name (required)</label>
    <input type="text" tabindex="1" size="22" value="" id="author" name="author"/>
    <%= Html.ValidationMessage("Author")%></p>
    <p><label for="email">E-mail (will not be published) (required)</label>
    <input type="text" size="22" tabindex="2" value="" id="email" name="email"/>
    <%= Html.ValidationMessage("Email")%></p>
    <p><label for="url">Website</label>
    <input type="text" tabindex="3" size="22" value="" id="Website" name="Website"/></p> 

    <p><%= Html.ValidationMessage("Content")%>
    <textarea tabindex="4" rows="10" cols="5" id="commentContent" name="content"></textarea></p> 

    <p><input type="submit" value="Submit Comment" tabindex="5" id="submit" name="submit"/>
    <span id="loading" style="display:none;">資料處理中</span>
    <input type="hidden" value="<%= ViewData.Model.Id %>" id="comment_post_ID" name="comment_post_ID"/></p>
</form>
<script type="text/javascript" language="javascript">
    function clearComment(a, b, c, d) {
        $get("commentContent").value = "";
    }    
</script>
<% } %>
</div> 

以上為使用M$的AJAX架構來實現AJAX非同步請求,下面來看看使用jQuery怎麼做呢。前面說過,我個人比較喜歡jQuery,所以樣本的4mvcBlog裡面的將使用jQuery來實現。

首先,我們用jQuery寫一個用於提交form表單的非同步請求的小"外掛程式":

(function($) {
    $.fn.ajaxForm = function(success) {
        var form = $(this);
        var btn = form.find(":submit");
        form.submit(function() {
            $.ajax({
                url: form.attr("action"),
                type: form.attr("method"),
                data: form.serialize(),
                beforeSend: function(xhr) {
                    btn.attr("disabled", true);
                    showLoading();
                },
                success: function(data) {
                    if (success) { success(data); }
                },
                error: function() {
                    alert("請求出錯,請重試");
                },
                complete: function() {
                    btn.attr("disabled", false);
                    hideLoading();
                }
            });
            return false;
        });
    };
    function showLoading() {
        $("#loading").css("display", "");
    };
    function hideLoading() {
        $("#loading").css("display", "none");
    };
})(jQuery); 

 

然後我們不需要修改原來的一般的form,我們只需要使用ajaxForm 方法來指定要進行ajax請求的form的id就可以了:

<form id="commentform" method="post" action="<%= Url.Action("AddComment",new{controller="Home",id=""}) %>"> 

<h3 id="respond">發表評論</h3>
    <p>歡迎留下你的評論,你的支援,是我最大的動力!</p>
    <p><label for="author">Name (required)</label>
    <input type="text" tabindex="1" size="22" value="" id="author" name="author"/>
    <%= Html.ValidationMessage("Author")%></p>
    <p><label for="email">E-mail (will not be published) (required)</label>
    <input type="text" size="22" tabindex="2" value="" id="email" name="email"/>
    <%= Html.ValidationMessage("Email")%></p>
    <p><label for="url">Website</label>
    <input type="text" tabindex="3" size="22" value="" id="Website" name="Website"/></p> 

    <p><%= Html.ValidationMessage("Content")%>
    <textarea tabindex="4" rows="10" cols="5" id="commentContent" name="content"></textarea></p> 

    <p><input type="submit" value="Submit Comment" tabindex="5" id="submit" name="submit"/>
    <span id="loading" style="display:none;">資料處理中</span>
    <input type="hidden" value="<%= ViewData.Model.Id %>" id="comment_post_ID" name="comment_post_ID"/></p>
</form>


<script type="text/javascript" language="javascript">    

//我們只需要在這裡註冊一下事件就可以,這就是jQuery和Html乾淨的分離的優雅。
$("#commentform").ajaxForm(success);
    function success(data) {
        if (data.search(/^\{[\s\S]+\}$/img) > -1) {
            alert(eval("(" + data + ")").ErrorMsg.toString());
        } else {
            var c = $(".boxcomments");
            if (c.length <= 0) {
                c = $(‘<div class="boxcomments"></div>‘);
                c.insertBefore("#commentform");
            }
            c.html($(data).find(".boxcomments").html());
            $("#commentContent").val("");
        }
    } 

</script>

後台代碼如下:


[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put), CallByAjax(true)]
public ActionResult AddCommentByAjax(FormCollection form)
{
    JsonResultData jsonData = new JsonResultData();
    Comment comment = new Comment();
    string postId = form["comment_post_ID"] ?? "";
    Post post = Post.GetPost(new Guid(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; 

            string website = form["Website"] ?? "";
            if (website.Trim().Length > 0)
            {
                if (!website.ToLowerInvariant().Contains("://"))
                    website = "http://"/ + website; 

                Uri url;
                if (Uri.TryCreate(website, UriKind.Absolute, out url))
                    comment.Website = url;
            } 

            post.AddComment(comment);
            SetCommentCookie(comment.Author, comment.Email, website, comment.Country);
            return View("_commentList", post.Comments);
        }
        else
        {
            foreach (string key in comment.BrokenRules.Keys)
            {
                //將驗證不通過的資訊添加到錯誤資訊列表
                jsonData.ErrorMsg.Add(comment.BrokenRules[key]);
            }
        }
    }
    jsonData.IsError = true;
    return Json_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

[轉]ASP.NET MVC 入門11、使用AJAX

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.