Go Getting Started with ASP 11, using Ajax

Source: Internet
Author: User

Before the ASP. NET MVC Beta release, m$ announced support for the Open source JS framework jquery, then ASP. After you build an ASP. NET MVC Beta project, You can find the ASP. NET AJAX and jquery JS in the project's scripts directory. Anyway, I prefer jquery, so it's very comforting for m$.

Needless to say, we use AJAX to implement the function of commenting. Let's take a look at how to use m$ 's JS framework for asynchronous AJAX requests.

First of all, of course is to introduce the m$ of the AJAX framework JS:

<script src= "/content/microsoftajax.js" type= "Text/javascript" ></script>
<script src= "/content/microsoftmvcajax.js" type= "Text/javascript" ></script>

The helper method of the ASP. NET MVC Framework provides support for his own Ajax, using the methods below the System.Web.Mvc.Ajax namespace. You can write code like this:

Or:

There is no EndForm method in Ajaxhelper, you can write HTML directly to close the form, or you can use Html.endform () to close it. Well, let's write a comment on the ajaxform:

Here is a detailed ajaxoptions of the functions of the various properties of the optional configuration.

public string Confirm: No test, do not know what to use, know to say.
public string HttpMethod: is the HTTP method that specifies the request, "POST" "GET" "PUT" and so on
Public Insertionmode Insertionmode: Returns the way the content is to be updated by the target element. There are three ways of doing this:
Replace: Replaces the contents of the target element;
InsertBefore: The return content is inserted in front of the target element;
InsertAfter: The return content is inserted after the target element.

public string Loadingelementid: Specifies the ID of the loading element for the prompt to display when an asynchronous request is made
public string Onbegin: JavaScript method triggered before sending an asynchronous request
public string OnComplete: JavaScript method triggered after sending asynchronous request completion
public string OnFailure: JavaScript method triggered when sending an asynchronous request fails
public string Onsuccess: The JavaScript method that is triggered when the asynchronous request is sent successfully
public string Updatetargetid: Specifies the ID of the target element to be updated by the returned content
public string URL: The URL of the requested URL, which is not specified as the action of the form.

In the above code, when the asynchronous request succeeds, a JavaScript method named Clearcomment is called to clear the comment of the input box, and then the content is replaced with the contents of the ID boxcomments element. The complete client code is as follows:


<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"});
%>

<p> Welcome to leave your comments, your support, is my biggest motivation!</p>
<p><label for= "Author" >name (required) </label>
<input type= "Text" tabindex= "1" size= "" value= "" id= "author" name= "Author"/>
<%= html.validationmessage ("Author")%></p>
<p><label for= "Email" >e-mail (won't be published) (required) </label>
<input type= "text" size= "tabindex=" 2 "value=" "id=" email name= "Email"/>
<%= html.validationmessage ("Email")%></p>
<p><label for= "url" >Website</label>
<input type= "Text" tabindex= "3" size= "" value= "" id= "Website" name= "Website"/></p>

<p><%= html.validationmessage ("Content")%>
<textarea tabindex= "4" rows= "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;" > Data Processing </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>

These are the Ajax frameworks that use m$ to implement AJAX asynchronous requests, so let's look at how jquery does it. As I said earlier, I personally prefer jquery, so the example 4mvcBlog will be implemented using jquery.

First, we use jquery to write a small "plug-in" that submits an asynchronous request for form forms:

(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 ("Request error, please retry");
},
Complete:function (){
Btn.attr ("Disabled", false);
Hideloading ();
}
});
return false;
});
};
function showloading (){
$ ("#loading"). CSS ("Display", "");
};
function hideloading () {
$ ("#loading"). CSS ("display", "none");
};
}) (JQuery);

Then we do not need to modify the original normal form, we just need to use the Ajaxform method to specify the ID of the form to make the AJAX request:

<form id= "Commentform" method= "post" action= "<%= url.action (" AddComment ", new{controller=" Home ", Id=" "})%>" >

<p> Welcome to leave your comments, your support, is my biggest motivation!</p>
<p><label for= "Author" >name (required) </label>
<input type= "Text" tabindex= "1" size= "" value= "" id= "author" name= "Author"/>
<%= html.validationmessage ("Author")%></p>
<p><label for= "Email" >e-mail (won't be published) (required) </label>
<input type= "text" size= "tabindex=" 2 "value=" "id=" email name= "Email"/>
<%= html.validationmessage ("Email")%></p>
<p><label for= "url" >Website</label>
<input type= "Text" tabindex= "3" size= "" value= "" id= "Website" name= "Website"/></p>

<p><%= html.validationmessage ("Content")%>
<textarea tabindex= "4" rows= "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;" > Data Processing </span>
<input type= "hidden" value= "<%= ViewData.Model.Id%>" id= "comment_post_id" name= "comment_post_id"/></ P>
</form>


<script type= "Text/javascript" language= "JavaScript" >

We just need to register the event here, which is the elegance of the clean separation of jquery and 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>

The background code is as follows:


[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)
{
Add information that is not validated to the error message list
JsonData.ErrorMsg.Add (comment. Brokenrules[key]);
}
}
}
Jsondata.iserror = true;
Return json_net (Jsondata);//If the business logic validation does not pass, the failure information represented by the Json result is returned
}

For the [Callbyajax (true)] attribute of the above background code, you can refer to my ASP. NET MVC Preview 5 Experience-an article that implements Actionselectionattribute to determine whether to choose a different action for an AJAX request.

Let's get here for the time being. enjoy! For specific effects please download the sample code to run the view or to the demo site http://4mvcblog.qsh.in/view. Post by Q.lee.lulu.

The latest Blog Sample program code: 4mvcblog_10.rar

Go Getting Started with ASP 11, using Ajax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.