2011-12-13 143 views
28

我想要的是從View(使用jquery/ajax)將txtComments的值傳遞給Controller。JQUERY ajax從MVC視圖傳遞值到控制器

問題是,ajax/jquery不接受script標籤作爲字符串。這意味着,當我在txtComments中輸入任何腳本/ html標籤時,ajax進入錯誤功能並且無法進入控制器。

這裏是jQuery的:

 $('#btnSaveComments').click(function() { 
      var comments = $('#txtComments').val(); 
      var selectedId = $('#hdnSelectedId').val(); 

      $.ajax({ 
       url: '<%: Url.Action("SaveComments")%>?id=' + selectedId + '&comments=' + escape(comments), 
       type: "post", 
       cache: false, 
       success: function (savingStatus) { 
        $("#hdnOrigComments").val($('#txtComments').val()); 
        $('#lblCommentsNotification').text(savingStatus); 
       }, 
       error: function (xhr, ajaxOptions, thrownError) { 
        $('#lblCommentsNotification').text("Error encountered while saving the comments."); 
       } 
      }); 
     }); 

這裏是控制器:

 [HttpPost] 
     public ActionResult SaveComments(int id, string comments){ 
      var actions = new Actions(User.Identity.Name); 
      var status = actions.SaveComments(id, comments); 
      return Content(status); 
     } 

我也試過$('#txtComments').serialize()而不是逃逸(評論),但仍是相同的。

+0

我面臨同樣的問題!你是如何解決它的? – moji

回答

42

嘗試使用$.ajax函數的data選項。更多信息here

$('#btnSaveComments').click(function() { 
    var comments = $('#txtComments').val(); 
    var selectedId = $('#hdnSelectedId').val(); 

    $.ajax({ 
     url: '<%: Url.Action("SaveComments")%>', 
     data: { 'id' : selectedId, 'comments' : comments }, 
     type: "post", 
     cache: false, 
     success: function (savingStatus) { 
      $("#hdnOrigComments").val($('#txtComments').val()); 
      $('#lblCommentsNotification').text(savingStatus); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      $('#lblCommentsNotification').text("Error encountered while saving the comments."); 
     } 
    }); 
}); 
+0

謝謝!有效。我只是將代碼修改爲數據:{'id':selectedId,'comments':escape(comments)}所以jquery/ajax會接受它。 – cjBognot

5
$('#btnSaveComments').click(function() { 
    var comments = $('#txtComments').val(); 
    var selectedId = $('#hdnSelectedId').val(); 

    $.ajax({ 
     url: '<%: Url.Action("SaveComments")%>', 
     data: { 'id' : selectedId, 'comments' : comments }, 
     type: "post", 
     cache: false, 
     success: function (savingStatu`enter code here`s) { 
      $("#hdnOrigComments").val($('#txtComments').val()); 
      $('#lblCommentsNotification').text(savingStatus); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      $('#lblCommentsNotification').text("Error encountered while saving the comments."); 
     } 
    }); 
}); 
6

這裏做同樣的電話的另一種方式。而你的類型應該總是在CAPS中,例如。鍵入:「GET」/ type:「POST」。

$.ajax({ 
     url:/ControllerName/ActionName, 
     data: "id=" + Id + "&param2=" + param2, 
     type: "GET", 
     success: function(data){ 
      // code here 
     }, 
     error: function(passParams){ 
      // code here 
     } 
}); 

另一種替代方法將是使用數據的Ajax的鏈路上。

<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a> 

假設ü曾與一個div我_content,這將調用的行動,並替換從操作返回的數據該分區中的內容。

<div id="_content"></div> 

不是真的直接回答你的問題,但它的一些信息你應該知道;)。

0
View Data 
============== 


@model IEnumerable<DemoApp.Models.BankInfo> 
<p> 
    <b>Search Results</b> 
</p> 
@if (!Model.Any()) 
{ 
    <tr> 
     <td colspan="4" style="text-align:center"> 
      No Bank(s) found 
     </td> 
    </tr> 
} 
else 
{ 
    <table class="table"> 
     <tr> 
      <th> 
       @Html.DisplayNameFor(model => model.Name) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.Address) 
      </th> 
      <th> 
       @Html.DisplayNameFor(model => model.Postcode) 
      </th> 
      <th></th> 
     </tr> 

     @foreach (var item in Model) 
     { 
      <tr> 
       <td> 
        @Html.DisplayFor(modelItem => item.Name) 
       </td> 
       <td> 
        @Html.DisplayFor(modelItem => item.Address) 
       </td> 
       <td> 
        @Html.DisplayFor(modelItem => item.Postcode) 
       </td> 
       <td> 
        <input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" /> 
       </td> 
      </tr> 
     } 
    </table> 
} 


<script src="~/Scripts/jquery-1.10.2.min.js"></script> 
<script type="text/javascript"> 
    $(function() { 
     $("#btnSearch").off("click.search").on("click.search", function() { 
      if ($("#SearchBy").val() != '') { 
       $.ajax({ 
        url: '/home/searchByName', 
        data: { 'name': $("#SearchBy").val() }, 
        dataType: 'html', 
        success: function (data) { 
         $('#dvBanks').html(data); 
        } 
       }); 
      } 
      else { 
       alert('Please enter Bank Name'); 
      } 
     }); 
} 
}); 


public ActionResult SearchByName(string name) 
     { 
      var banks = GetBanksInfo(); 
      var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList(); 
      return PartialView("_banks", filteredBanks); 
     } 

     /// <summary> 
     /// Get List of Banks Basically it should get from Database 
     /// </summary> 
     /// <returns></returns> 
     private List<BankInfo> GetBanksInfo() 
     { 
      return new List<BankInfo> 
      { 
       new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" }, 
       new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" }, 
       new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" }, 
       new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" }, 
       new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" } 
      }; 
     } 
+2

如果你添加一些關於答案的評論,會很好! –

相關問題