簡體   English   中英

無法通過ViewBag在部分View的JQuery中發送參數。

[英]Can't send parameters by ViewBag in JQuery of partial View.

我正在開發一個帶有razor語法的MVC3應用程序。 我正在研究評論功能的部分類。

我的代碼是:

<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>

我試圖在上面的jQuery中使用ViewBag從View向控制器發送參數,但它無法正常工作。 我怎樣才能做到這一點?

試試這樣:

<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)
{
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM