2012-09-17 30 views
0

我正在開發一個帶有razor語法的MVC3應用程序。我正在研究評論功能的部分類。無法通過部分視圖的JQuery中的ViewBag發送參數。

我的代碼是:

<script src="../../Scripts/jquery.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#AddCommentButton').click(function() { 
      $.ajax({ 
       type: 'post', 
       url: '/Comment/SaveComments', 
       dataType: 'json', 
       data: 
       { 

       'comments': $('#Comment').val(), @ViewBag.EType, @ViewBag.EId 
       }, 

        success: function (data) { 

        $("p.p12").append 

        $('.ShowComments').text('Hide Comments'); 

       } 
      }); 
     }); 
    }); 
</script> 

我想參數發送到從視圖控制器,使用ViewBag,在上面的jQuery,但它不工作。我怎樣才能做到這一點?

+0

腳本中呈現了什麼值?你能告訴我們結果嗎? –

回答

2

嘗試這樣的:

<script src="@Url.Content("~/Scripts/jquery.js")" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#AddCommentButton').click(function() { 
      $.ajax({ 
       type: 'post', 
       url: '@Url.Action("SaveComments", "Comment")', 
       data: { 
        comments: $('#Comment').val(), 
        etype: @Html.Raw(Json.Encode(ViewBag.EType)), 
        eid: @Html.Raw(Json.Encode(ViewBag.EId)) 
       }, 
       success: function (data) { 
        $("p.p12").append(data); 
        $('.ShowComments').text('Hide Comments'); 
       } 
      }); 
     }); 
    }); 
</script> 

和你的控制器動作:

[HttpPost] 
public ActionResult SaveComments(string comments, string etype, string eid) 
{ 
    ... 
} 

或定義視圖模式:

public class SaveCommentViewModel 
{ 
    public string Comments { get; set; } 
    public string EType { get; set; } 
    public string EId { get; set; } 
} 

然後:

[HttpPost] 
public ActionResult SaveComments(SaveCommentViewModel model) 
{ 
    ... 
} 
+0

謝謝,但我不想傳遞視圖模型,我想作爲一個單獨的參數發送。像這樣'public JsonResult SaveComments(字符串註釋,字符串EType,字符串EId)' – user1668543

+0

然後我的第一個例子應該爲你工作。 –

+0

不工作...我輸入SMAE因爲它是...'評論:$( '#評論')VAL(), VLAN時:@ Html.Raw(Json.Encode(ViewBag.EType)), EID :@ ViewBag.EId它顯示警告 - '{'預計接近Comment和';'預計在EType附近。 ' – user1668543

相關問題