2

i'm trying to update partial view but couldn't update. i'm sharing the code I have done so far.

Action:

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();
        }

this JQuery Code:

   $(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);
});

this is Partial View _Reviews:

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

this is Details View:

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

I have used and searched for lot of possible solution but I was unable to get the finest solution for this thing. please help me with this, where i'm making the error.

DevWithSigns
  • 725
  • 16
  • 33

2 Answers2

2

I have never seen an ajax built like that before. try changing your ajax call to this

$('.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);
        } 
    });
});

this will put the partial view that is returned into a div with class divPartial

Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • your code is not working, actually I want to update the partial view, everything else is working fine but after the form will post, the partial view is not updating on submit but call to controller is done successfully – DevWithSigns Feb 22 '14 at 21:20
  • this will update the partial view. This will fire on the click of a button with class btnSubmit. What isn't working about it? – Matt Bodily Feb 23 '14 at 02:06
  • @Matt That is not work. Please check my question about that in http://stackoverflow.com/questions/23033242/send-partial-view-model-and-update-partial-view-with-jquery-has-issues – QMaster Apr 13 '14 at 19:49
0

it looks like you are passing in a "Review" to your partial view, but your Partial view is expecting

IEnumerable<ConsumerSimpleNew.Models.Entities.Review> 

add an error: section to your jquery call and see if it gets hit?

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);
        }
Matt Tabor
  • 1,053
  • 8
  • 10
  • i have tried changing "Review" but got model item error, the partial view is not updating but the rest is working fine, – DevWithSigns Feb 23 '14 at 09:08
  • i have updated my answer, try passing reviewList into the PartialView as above – Matt Tabor Feb 23 '14 at 09:16
  • Thanks it is somewhat working fine but now when I submit the form it just display the new review but not the list of previous reviews and it is not emptying the text fields of page after submitting. – DevWithSigns Feb 23 '14 at 09:25
  • you have a few options: 1) create a new partialview for a SingleReview, and append this to your reviews i.e $target.replaceWith($newHtml) changes to $target.append($newHtml); or 2) get all your reviews again in your controller and pass all the reviews back again. with regards to emptying the text fields you can do this manually in javascript. – Matt Tabor Feb 23 '14 at 09:34
  • I did the same as u write but now it is working if there is at least one review in list otherwise I have to refresh the page to see the changes. it is working fine if there are existing reviews at least one. why is this so? – DevWithSigns Feb 23 '14 at 09:43
  • which option did you try? – Matt Tabor Feb 23 '14 at 09:59
  • I have just replaced $target.replaceWith($newHtml) with $target.append($newHtml)..help me plz – DevWithSigns Feb 23 '14 at 11:08
  • are you able to update your question with all the updated code? then i may be able to spot where the issue is. – Matt Tabor Feb 23 '14 at 13:57
  • I have updated the Jquery code, u can check the edits – DevWithSigns Feb 23 '14 at 13:59
  • i think the issue will be in the ActionResult code, can you update that aswell? – Matt Tabor Feb 23 '14 at 14:02
  • ok i have changed the location in my answer of where the reviewsList is defined to inside the Request.IsAjaxRequest(). hopefullt this fixes your issue. – Matt Tabor Feb 23 '14 at 14:20
  • still the same issue :( – DevWithSigns Feb 23 '14 at 14:54