2013-04-20 40 views
11

Tôi đang cố gắng tìm hiểu MVC và một trong những điều tôi muốn làm là gửi biểu mẫu đến một hành động trong bộ điều khiển của tôi và hành động này sẽ trả về dữ liệu đã gửi. Nghe có vẻ đơn giản nhưng tôi đã cố gắng hàng giờ mà không thành công. quan điểm của tôi:Gửi mẫu với jquery ajax

@using (Html.BeginForm("BlogComment","Blog")) 
{ 
    @Html.ValidationSummary(true) 
    <legend class="AddAComment">Add a comment</legend> 

    <div class="commentformwrapper"> 

     <div class="editor-text"> 
     <span class="editor-label">User Name:</span> 
     </div> 

     <div class="editor-text"> 
     <input type="text" id="username" /> 
     </div> 

     <div class="editor-text"> 
     <textarea id="comment" rows="6" cols="23"></textarea> 
     </div> 

     <div class="editor-field"> 
     <input type="hidden" id="hiddendate" /> 
     </div> 

     <input type="submit" id="submit" value="Create" /> 

    </div> 
} 

điều khiển của tôi:

[HttpPost] 
public ActionResult CommentForm(Comment comment) 
{ 
    Comment ajaxComment = new Comment(); 
    ajaxComment.CommentText = comment.UserName; 
    ajaxComment.DateCreated = comment.DateCreated; 
    ajaxComment.PostId = comment.PostId; 
    ajaxComment.UserName = comment.UserName; 

    mRep.Add(ajaxComment); 
    uow.Save(); 
    //Get all the comments for the given post id 

    return Json(ajaxComment); 
} 

và js của tôi:

$(document).ready(function() { 

     $('form').submit(function() { 

      $.ajax({ 
       url: '@Url.Action("CommentForm")', 
       type: "POST", 
       dataType: "json", 
       contentType: "application/json; charset=utf-8", 
       data: { 
        PostId: $('.postid').val(), 
        UserName: $('#username').val(), 
        DateCreated: new Date(), 
        CommentText: $('#comment').val() 
       }, 
       success: function (result) { 

        alert("success " + result.UserName); 
       }, 
       error: function (result) { 
        alert("Failed"); 
       } 
      }); 
      return false; 
     }); 
    }); 
+0

vấn đề của bạn là gì? Điều gì không hoạt động? – nemesv

+0

bạn đang thiếu JSON.stringify() –

Trả lời

10

Về cơ bản bạn đang chuyển trực tiếp các đối tượng javascript trực tiếp. Vì vậy, trước khi bạn truyền dữ liệu cho bộ điều khiển của mình, nó phải ở định dạng JSON (vì bạn đã chỉ định ứng dụng/json. Hãy xem cuộc gọi $ .ajax của bạn).
SO, bạn đang thiếu JSON.stringify()

data: JSON.stringify({ 
         PostId: $('.postid').val(), 
         UserName: $('#username').val(), 
         DateCreated: new Date(), 
         CommentText: $('#comment').val() 
        }), 

HOẶC

var someObj = { 
      PostId: $('.postid').val(), 
      UserName: $('#username').val(), 
      DateCreated: new Date(), 
      CommentText: $('#comment').val() 
     }; 

     $.ajax({ 
      /// your other code 
      data: JSON.stringify(someObj), 
      // your rest of the code 

     }); 
+0

Điều này làm cho nó hoạt động nhờ! – user2302622

4

Thay vì

data: { 
      PostId: $('.postid').val(), 
      UserName: $('#username').val(), 
      DateCreated: new Date(), 
      CommentText: $('#comment').val() 
     }, 

Hãy thử

$('form').submit(function() { 
    var obj = { 
     PostId: $('.postid').val(), 
     UserName: $('#username').val(), 
     DateCreated: new Date(), 
     CommentText: $('#comment').val() 
    }; 

    $.ajax({ 
     ..., 
     data: JSON.stringify(obj), 
     ..., 
    }); 

    return false; 
}); 

Bạn phải chuyển đổi dữ liệu thành chuỗi trước khi gửi đến máy chủ. và JSON.stringify hiện công việc đó

+0

Tôi đã thử nó chính xác như thế này và nó không hoạt động. Kỳ lạ là tôi đã thử những gì DotNet Dreamer đã nói và nó hoạt động. – user2302622

+0

Điều này thật kỳ lạ và vô lý. Những gì DotNet Dreamer nói là chính xác những gì tôi đã nói. Có nghĩa là, Nếu giải pháp của anh ấy đang hoạt động thì giải pháp của tôi đang hoạt động. –

21

Bạn không cần mã phía khách hàng để thực hiện điều này, FYI.

Để sử dụng các phương thức ajax thành công trong MVC, bạn sẽ cần thực hiện các thao tác sau. Thêm phím này để appSettings trong web.config:

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

Cũng như bao gồm kịch bản ajax không phô trương:

<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> 

Sau đó tạo div container xung quanh hình thức của bạn và thay thế Html.BeginForm với Ajax.BeginForm

<div id="ajaxReplace"> 
@using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" })) 
{ 
@Html.ValidationSummary(true) 
     <legend class="AddAComment">Add a comment</legend> 

     <div class="commentformwrapper"> 

      <div class="editor-text"> 
      <span class="editor-label">User Name:</span> 
      </div> 

      <div class="editor-text"> 
      <input type="text" id="username" /> 
      </div> 

      <div class="editor-text"> 
      <textarea id="comment" rows="6" cols="23"></textarea> 
      </div> 

      <div class="editor-field"> 
      <input type="hidden" id="hiddendate" /> 
      </div> 

      <input type="submit" id="submit" value="Create" /> 

     </div> 

    } 
</div> 

Sau đó, trong bộ điều khiển của bạn, bạn sẽ quay trở lại một cái gì đó như thế này:

return PartialView(ajaxComment); 

Điều này sẽ giúp bạn duy trì một tập lệnh để thực hiện việc này theo cách thủ công và sẽ đưa bạn vào sử dụng khung như dự định. Nó cũng sẽ giúp bạn ra ngoài với xác nhận chú thích dữ liệu và tất cả những thứ ngon ngọt đi kèm với nó,

Tôi hy vọng điều này sẽ giúp theo một cách nào đó.

+0

Cảm ơn bạn đã gợi ý, tôi sẽ ghi nhớ điều này trong lần sau. Bây giờ tôi sẽ chỉ dính vào ajax jquery đơn giản. – user2302622

+2

Tôi nghĩ rằng Jquery ajax rất giàu tính linh hoạt nhưng khi nói đến các mã Validation Summary, vv MVC tự xử lý nó là một người chiến thắng rõ ràng khi so sánh RenderPartialView với kiểu trả về Json. –

+0

@ShyamalParikh Tôi đồng ý với cả hai tuyên bố của bạn. Tôi đã không sử dụng phương pháp ở trên trước đây và nó dễ dàng hơn so với dây nó lên bản thân mình. Tôi ước tôi đã biết về điều này sớm hơn. Cảm ơn một lần nữa để OP –

13

Hãy thử điều này:

Model

public class Comment 
{ 
    public string CommentText { get; set; } 
    public DateTime? DateCreated { get; set; } 
    public long PostId { get; set; } 
    public string UserName { get; set; } 
} 

The View và js

@model SubmitMvcForWithJQueryAjax.Models.Comment 

@using (Html.BeginForm("BlogComment","Blog")) 
{ 
    @Html.ValidationSummary(true) 
    <legend class="AddAComment">Add a comment</legend> 

    <div class="commentformwrapper"> 

     <div class="editor-text"> 
     <span class="editor-label">User Name:</span> 
     </div> 

     <div class="editor-text"> 
      @Html.EditorFor(m => m.UserName) 
     </div> 

     <div class="editor-text"> 
      @Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"}) 
     </div> 

     <div class="editor-field"> 
      @Html.HiddenFor(m => m.DateCreated)   
     </div> 

     <div class="editor-field"> 
      @Html.HiddenFor(m => m.PostId)   
     </div> 

     <input type="submit" id="submit" value="Create" /> 

    </div> 

} 

<script type="text/javascript"> 
    $(document).ready(function() { 

     $('form').submit(function() { 
      var serializedForm = $(this).serialize();      
      $.ajax({ 
       url: '@Url.Action("CommentForm")', 
       type: "POST",          
       data: serializedForm, 
       success: function (result) { 

        alert("success " + result.UserName); 
       }, 
       error: function (result) { 
        alert("Failed"); 
       } 

      }); 
      return false; 
     }); 
    }); 

</script> 

Controller

public class CommentController : Controller 
{ 
    // 
    // GET: /Comment/ 

    public ActionResult Index() 
    { 
     return View(new Comment()); 
    } 

    [HttpPost] 
    public ActionResult CommentForm(Comment comment) 
    { 
     Comment ajaxComment = new Comment(); 
     ajaxComment.CommentText = comment.UserName; 
     ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now; 
     ajaxComment.PostId = comment.PostId; 
     ajaxComment.UserName = comment.UserName; 

     //mRep.Add(ajaxComment); 
     //uow.Save(); 
     //Get all the comments for the given post id 

     return Json(ajaxComment); 


    } 

} 
+0

cảm ơn cho đề nghị, nhưng tôi tin rằng quan điểm của tôi đã được đánh mạnh mẽ (bình luận) cho serialization để làm việc và đây không phải là trường hợp của tôi. – user2302622

Các vấn đề liên quan