0

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 からコントローラーにパラメーターを送信しようとしていますが、機能していません。どうやってやるの?

4

1 に答える 1

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)
{
    ...
}
于 2012-09-17T05:23:46.673 に答える