How to use JSon data in mvc action and post form data use JQuery ajax

原文连接: http://www.flyear.net/Artical/How-To-Use-JSon-Data-In-MVC-Action-and-post-form-data-use-jquery-ajax

1. Front-End Html:

  1. @using (Html.BeginForm("NewComment", "Home", new { area = "Blog" }, FormMethod.Post, new { id = "commentForm" }))
  2. {
  3.     <hr />
  4.     <input id="articalId" type="hidden" value="@Model.Post.PostID" />
  5.     <ul>
  6.         <li><span>User</span><input id="commenterName" type="text" /></li>
  7.         <li><span>Email</span><input id="commenterEmail" type="text" /></li>
  8.         <li><span>Site</span><input id="commenterSite" type="text" /></li>
  9.         <li><span>Comment Content</span><p>
  10.             <textarea id="commenterContent" cols="35" rows="10"></textarea></p>
  11.         </li>
  12.         <li>
  13.             <input id="commentSubmit" type="submit" value="Submit" /></li>
  14.     </ul>
  15. }

 

2. Front-End JavaScript:

  1. $("#commentForm").submit(function () {
  2.             var odata = GetCurrentComment();
  3.             if (oldSubmitComment != null || oldSubmitComment != undefined) {
  4.                 if (odata.Content == oldSubmitComment.Content) {
  5.                     $("#msg").html("<span style=\"color: Red\"><strong>You already submited this comment, please add new content for submit.</strong></span>");
  6.                     return false;
  7.                 }
  8.             }
  9.             oldSubmitComment = odata; //Set old submit comment to current submit data
  10.             var json_strng = JSON.stringify(odata);
  11.             var beforeDate = new Date();
  12.  
  13.             $.ajax({
  14.                 url: $("#commentForm").attr("action"),
  15.                 type: 'POST',
  16.                 contentType: 'application/json',
  17.                 dataType: 'json',
  18.                 data: json_strng,
  19.                 success: function (result, status) {
  20.                     if (result.Success) {
  21.                         AppenderNewCommentToEnd(odata);
  22.                         var completeDate = new Date();
  23.                         $("#msg").html("Your spend <span style=\"color: Red\"><strong>" + (completeDate - beforeDate) + " Milliseconds </strong></span>on this submit, Thanks for your time.");
  24.                     }
  25.                     else {
  26.                         $("#msg").html("<span style=\"color: Red\"><strong>Your submit fauiler, Detail message is:" + json2.ErrorMessage + "</strong></span>");
  27.                     }
  28.                 }
  29.             });
  30.             return false;
  31.         });

 

 

  1. function TrArticalComment(articalId, name, email, site, date, content) {
  2.         this.PostID = articalId;
  3.         this.UserName = name;
  4.         this.Email = email;
  5.         this.WebAddress = site;
  6.         this.Date = date;
  7.         this.Content = content;
  8.     }
  9.     //Page Transfer Model       
  10.     function GetCurrentComment() {
  11.         var comment = new TrArticalComment(
  12.                 $("#articalId").val(),
  13.                 $("#commenterName").val(),
  14.                 $("#commenterEmail").val(),
  15.                 $("#commenterSite").val(),
  16.                 new Date(),
  17.                 $("#commenterContent").val());
  18.         return comment;
  19.     }
  20.     function AppenderNewCommentToEnd(comment) {
  21.         $("<hr/><div class=\"commentHeader\"> <a href='" + comment.WebAddress + "' target=\"_blank\"><span class=\"commentUser\">" + comment.UserName + "</span></a> <span class=\"commonDate\">"
  22.                 + comment.Date + "</span></div><div class=\"commonContent\">" + comment.Content + "</div>").appendTo("#newCommentHere");
  23.     }

 

3. Back-End code:

  1. [HttpPost]
  2.         public JsonResult NewComment(NewCommentDto comment)
  3.         {
  4.             var pComment = comment.ToPostComment();
  5.             PostService.AddComment(pComment.PostID, pComment);
  6.             return Json(new { Success = true, Message = "Successfully" });
  7.         }

 

4. Some things need more attentation:

We need add ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); into Application_Start method in Global.axsx.cs to support Action receive JSon format data.

 

  1. protected void Application_Start()
  2.         {
  3.             logger.Info("LightBlog log system started.");
  4.  
  5.             LightBlog.Infrastructure.RepositoryFramework.NHibernateProvider.DataContext.ReCreateDatabase();
  6.  
  7.             AreaRegistration.RegisterAllAreas();
  8.  
  9.             RegisterGlobalFilters(GlobalFilters.Filters);
  10.             RegisterRoutes(RouteTable.Routes);
  11.  
  12.             ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
  13.  
  14.         }
posted @ 2011-09-20 23:21  DukeCheng  阅读(927)  评论(0编辑  收藏  举报