通过Ajax将值传递给控制器​​MVC 4

时间:2014-03-11 02:25:26

标签: jquery ajax asp.net-mvc-4

尝试通过ajax将两个值传递给我的ArticleController中的SaveRating方法。传递给ajax(artID,v)的两个值都会检出正确的值。我总是从ajax得到错误警告,无法找出原因。

//编辑:可能的原因:

以下是从here的教程中获取的代码。这最初是在webform中完成的,但我是在视图中完成的。

在本教程中使用了这行代码,

<div class="rating-star-block" id='div_<%#Container.DataItemIndex %>'>

我不知道如何处理它所以我用,

代替
<div class="rating-star-block" id="div_@Html.DisplayFor(model => model.ID)"> 

这是在ajax中调用的,因为updateP等于class =“rating-star-block”的id:

var updateP = "#" + $(this).parent().attr('id') + ' .CurrentScore';

抓住了id:

id="div_@Html.DisplayFor(model => model.ID)">  

另外......在我的错误提示中,我得到“未定义”。

这是我的Ajax:

        $.ajax({
            type: "POST",
            url: "/Article/SaveRating",
            data: "{articleID: '" + artID + "',rate: '" + v + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                setNewScore(updateP, data.d);
            },
            error: function (data) {
                alert(data.d);
            }
        });

这是我的控制器:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static int SaveRating(int articleID, int rate)
    {
        LearningEnterprises.DAL.ArticleEntities db = new LearningEnterprises.DAL.ArticleEntities();

        int result = 0;

        {

            db.ArticleScores.Add(new ArticleScore
            {
                ArticleID = articleID,
                ScoreID = 0,
                Score = rate,
                ScoreCreated = DateTime.Now
            });
            db.SaveChanges();

            var newScore = (from a in db.ArticleScores
                            where a.ArticleID.Equals(articleID)
                            group a by a.ArticleID into aa
                            select new
                            {
                                Score = aa.Sum(a => a.Score) / aa.Count()
                            }).FirstOrDefault();
            result = newScore.Score;
        }
        return result;
    }

添加其余视图:

@model LearningEnterprises.Models.Article

...

<style>
    .rating-star-block .star.outline {
        background: url("/images/star-empty-lg.png") no-repeat scroll 0 0 rgba(0,0,0,0);
    }
    .rating-star-block .star.filled {
        background: url("/images/star-fill-lg.png") no-repeat scroll 0 0 rgba(0,0,0,0);
    }
    .rating-star-block .star {
        color: rgba(0,0,0,0);
        display: inline-block;
        height: 24px;
        overflow: hidden;
        text-indent: -999em;
        width: 24px;
    }
    a {
        color: #005782;
        text-decoration: none;
    }
</style>    

    <div class="rating-star-block" id="div_@Html.DisplayFor(model => model.ID)">
        <input type ="hidden" class="articleID" value = "@Html.DisplayFor(model => model.ID)" />
        Current Score: <span class="CurrentScore">@Html.DisplayFor(model => model.Score)</span><br /><div class="yourScore">Your Score : </div>
        <a class="star outline" href="#" rating="1" title="vote 1"> vote 1</a>
        <a class="star outline" href="#" rating="2" title="vote 2"> vote 2</a>
        <a class="star outline" href="#" rating="3" title="vote 3"> vote 3</a>
        <a class="star outline" href="#" rating="4" title="vote 4"> vote 4</a>
        <a class="star outline" href="#" rating="5" title="vote 5"> vote 5</a>
    </div>
    <div id="myElem" style="position:absolute; top:10px; left:50%; display:none; background-color:yellow; padding:5px; border: 1px solid red">
        Thank you for your rating!
    </div>

...

<script>



    $(".rating-star-block .star").mouseleave(function () {
            $("#" + $(this).parent().attr('id') + " .star").each(function () {
                $(this).addClass("outline");
                $(this).removeClass("filled");

            });
        });
        $(".rating-star-block .star").mouseenter(function () {
            var hoverVal = $(this).attr('rating');
            $(this).prevUntil().addClass("filled");
            $(this).addClass("filled");
            $("#RAT").html(hoverVal);

        });
        $(".rating-star-block .star").click(function () {

            var v = $(this).attr('rating');
            var newScore = 0;
            var updateP = "#" + $(this).parent().attr('id') + ' .CurrentScore';
            var artID = $("#" + $(this).parent().attr('id') + ' .articleID').val();


            $("#" + $(this).parent().attr('id') + " .star").hide();
            $("#" + $(this).parent().attr('id') + " .yourScore").html("Your Score is : &nbsp;<b style='color:#ff9900; font-size:15px'>" + v + "</b>");
            $.ajax({ ...
                }
            });
        });

    function setNewScore(container, data) {
        $(container).html(data);
        $("#myElem").show('1000').delay(2000).queue(function (n) {
            $(this).hide(); n();
        });
    }
</script>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

1 个答案:

答案 0 :(得分:1)

使用:

data: { articleID: artID,
        rate: v
      },

您正在发送包含Javascript对象格式的字符串。您需要提供Javascript对象,jQuery会将其正确编码为POST数据。