无法使用mvc 4中的jquery ajax更新部分视图

时间:2014-02-22 20:08:04

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

我正在尝试更新部分视图但无法更新。我正在分享我到目前为止所做的代码。

动作:

public ActionResult AddReview([Bind(Include = "ReviewId,ProductId,ReviewerName,ReviewText,Rating,Time,Summary")]
            Review review, int? id)
        {



            var reviewsList = new List<Review>();
            reviewsList.Add(review);

            if (ModelState.IsValid)
            {
                review.Time = DateTime.Now;
                review.ProductId = id.Value;
                db.Reviews.Add(review);
                db.SaveChanges();
                if (Request.IsAjaxRequest())
                {
                    // return HttpNotFound();

                    return PartialView("_Reviews", reviewsList);
                }
            }



            return HttpNotFound();
        }

这个JQuery代码:

   $(function () {
    var ajaxFormSubmit = function () {
        var $form = $(this);
        var options = {
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: $form.serialize()
        };

        $.ajax(options).done(function (data) {
            var $target = $($form.attr("data-consumer-target"));
            var $newHtml = $(data);
         //   $target.replaceWith($newHtml);
            $target.append($newHtml);
            $newHtml.effect("highlight");
            success: alert('Thanks for your review');
            $("#ajax-contact-form").find('input, textarea').val("");


        });

        return false;
    };

    $("form[data-consumer-ajax='true'").submit(ajaxFormSubmit);
});

这是部分视图_评论:

@model IEnumerable<ConsumerSimpleNew.Models.Entities.Review>

<div id="reviews">
    @foreach (var item in Model)
    {
        <h5>
            <span class="color"> @Html.DisplayFor(modelitem => item.ReviewerName)</span> - @item.Time.ToString("MMM dd-yyyy")
        </h5>

        <h6>Summary - @Html.DisplayFor(modelitem => item.Summary)</h6>
        <h6>Rating: @Html.DisplayFor(modelitem => item.Rating)</h6>
        <div class="std">@Html.DisplayFor(modelitem => item.ReviewText)</div>
        <hr />
    }
</div>

这是详细信息视图:

 @Html.Partial("_Reviews", Model.Reviews)


                            <div class="form-add">
                                <h2>Write Your Own Review</h2>

                                <form method="post" action="@Url.Action("Details")"
                                      data-consumer-ajax="true" data-consumer-target="#reviews">


                                    @Html.AntiForgeryToken()
                                    @Html.ValidationSummary(true)

                                    <fieldset>
                                        <h4>You're reviewing: <span class="color">@Model.Product.Name</span></h4>

                                        <span id="input-message-box"></span>

                                        <input type="hidden" name="validate_rating"
                                               class="validate-rating" value=""><ul class="form-list">
                                            <li>
                                                <label for="nickname_field" class="required"><em>*</em>Name</label>
                                                <div class="input-box">
                                                    @Html.TextBoxFor(modelitem => Model.Review.ReviewerName, new
                                                {
                                                    @class = "input-text required-entry",
                                                    placeholder = "Write your name"
                                                })
                                                    @Html.ValidationMessageFor(model => model.Review.ReviewerName)

                                                </div>
                                            </li>
                                            <li>
                                                <label for="summary_field" class="required"><em>*</em>Summary of Your Review</label>
                                                <div class="input-box">
                                                    @Html.TextBoxFor(modelitem => Model.Review.Summary, new
                                                {
                                                    @class = "input-text required-entry",
                                                    placeholder = "Write Summary"
                                                })
                                                    @Html.ValidationMessageFor(model => model.Review.Summary)


                                                </div>
                                            </li>

                                            <li>
                                                <label for="summary_field" class="required"><em>*</em>Rating (out of 10)</label>
                                                <div class="input-box">
                                                    @Html.TextBoxFor(modelitem => Model.Review.Rating, new
                                                {
                                                    @class = "input-text required-entry",
                                                    placeholder = "Give Some Rating"
                                                })
                                                    @Html.ValidationMessageFor(model => model.Review.Rating)


                                                </div>
                                            </li>
                                            <li>
                                                <label for="review_field" class="required"><em>*</em>Review</label>
                                                <div class="input-box">
                                                    @Html.TextAreaFor(modelitem => Model.Review.ReviewText, new
                                                {
                                                    cols = "15",
                                                    rows = "13",
                                                    @class = "required-entry",
                                                    placeholder = "Write your review..."
                                                })
                                                    @Html.ValidationMessageFor(model => model.Review.ReviewText)


                                                </div>
                                            </li>
                                        </ul>
                                    </fieldset>
                                    <div class="buttons-set">
                                        <input type="submit" title="Submit Review" class="button pull-right" value="Submit Review" />
                                    </div>
                                </form>

我已经使用并搜索了很多可能的解决方案,但我无法获得最好的解决方案。请帮助我,我正在犯错误。

2 个答案:

答案 0 :(得分:2)

我以前从未见过这样的ajax。尝试将您的ajax调用更改为此

$('.btnSubmit').on('click', function(){
    $.ajax({
        url: '@Url.Action("Action", "Controller")',
        type: 'post',
        cache: false,
        async: true,
        data: { id: "frmUser" },
        success: function(result){
            $('.divPartial').html(result);
        } 
    });
});

这会将返回的部分视图放入div divPartial

的div中

答案 1 :(得分:0)

看起来你正在传递&#34;评论&#34;您的部分视图,但您的部分视图正在等待

IEnumerable<ConsumerSimpleNew.Models.Entities.Review> 

在你的jquery调用中添加一个错误:section并查看它是否被命中?

if (ModelState.IsValid)
        {
            review.Time = DateTime.Now;
            review.ProductId = id.Value;
            db.Reviews.Add(review);
            db.SaveChanges();
        }
        if (Request.IsAjaxRequest())
        {
           // return HttpNotFound();
        var reviewsList = new List<Review>();
        reviewsList.Add(review);

            return PartialView("_Reviews", reviewsList);
        }