0

I'm trying to make request returns on ajax updated partial view. Apparently request is not returned from the ajax-function. Here ajax-code:

<script type="text/javascript">
function doAjaxPost(myid) {
    // get the form values
    var ApplSort = $('#DropDownListSort').val();
    var radio_check_val=0;

    for (i = 0; i < document.getElementsByName('radio').length; i++) {
        if (document.getElementsByName('radio')[i].checked) {
            radio_check_val = document.getElementsByName('radio')[i].value;
        }
    }

    // alert("myid=" + myid +";"+ "ApplSort=" + ApplSort + ";" + "radio_check_val=" + radio_check_val);

    $.ajax(
 {
     type: 'POST',
     contentType: 'application/json; charset=utf-8',
     data: { ApplSort: ApplSort, radio_check_val: radio_check_val, myid: myid },
     UpdateTargetId: "tabledata",
     dataType: 'html',
     url: 'Partner/PartnerApplications',
     success: function (data) { 
      var result = data;
      $('tabledata').html(result);
},

     error: function (error) {
         alert('Ошибка AJAX-запроса. Обновите страницу!');
     }
 });
}
</script>

Fail is called and the page is completely updated.

Here's updated content in the view:

<div id="target">
@Html.Partial("~/Views/Partner/PartnerApplicationsPartial.cshtml")
</div>

controller's code:

[HttpPost]
    public ActionResult PartnerApplications(int[] ApplSort, int[] radio_check_val, int[] myid)
    {
        MordaPartner MrdPrt = new MordaPartner(Server, Request);

        if (Request.IsAjaxRequest())
        {
            var obj = MrdPrt.morda_obj.CookieAuthenticationPartner(Server, Request, Response, MrdPrt.PartnerLogin, MrdPrt.PartnerPassword);
            if (obj != null)
            {
                //alert("ApplSort=" + ApplSort + ";" + "ApplSelectOffer=" + ApplSelectOffer + ";" + "ApplSelectAuction=" + ApplSelectAuction + ";" + "ApplSelectNoOffer=" + ApplSelectNoOffer);

                var objs = from s in MrdPrt.morda_obj.entities.applications where s.application_user_city == obj.partner_city & s.application_blocked != 1 orderby s.application_id ascending select s;

                return Json(new { data = this.RenderPartialViewToString("PartnerApplicationsPartial", objs) });
            }
            else
            {
                return RedirectToAction("Registration");

            }
        }
        else { return RedirectToAction("PartnerApplications"); }
    }

RenderPartialViewToString it was taken from here: http://www.c-sharpcorner.com/blogs/7150/implementing-renderpartialviewtostring-in-asp-net-mvc-3.aspx

script is loaded:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

What am I doing wrong?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Kot Fantazer
  • 11
  • 1
  • 1
  • 4

2 Answers2

1

I think your easiest solution since you are just wanting to do a partial...

@using( Ajax.BeginForm( "PartnerApplications", 
                        null, 
                        new AjaxOptions() { 
                             HttpMethod = "POST", 
                             InsertionMode = InsertionMode.Replace,  
                             UpdateTargetId = "target", 
                             LoadingElementId = "AjaxSearch" }, 
                        new { id = "UserSearchForm" } ) ) {
    <input type="text" id="id" name="id" placeholder="Enter Search" />
}

This is an ability that is built into MVC that makes it VERY easy to update an element with the results of a partial.

All this is saying is that you want a new Ajax Form that calls the PartnerApplications Action. You want the action called with an HttpMethod that is a POST request and you want the results to replace (InsertionMode.Replace) the existing elements in the target (whatever that may be) and while the request is taking place you want the element AjaxSearch visible (this is optional, but something I use to show that it's working).

This will generate the required JavaScript for you and until you get into something beyond simply returning a partial works EXCELLENT!

EDIT: Also you will need to update your Action...

return Json(new { data = this.RenderPartialViewToString("PartnerApplicationsPartial", objs) });

needs changed to....

return PartialView("PartnerApplicationsPartial", objs);

EDIT BASED ON COMMENTS:

Without knowing the data better that is being sent to the server I can't tell you what to write in order to replace that method. I would however look at the properties of new AjaxOptions(){} because it has some additional properties that allow you to specify the name of a JavaScript function to call on four states (before/after/success/fail) of the Ajax request. So if you are needing to calculate something you can do this by specifying a JavaScript function that will be processed before the Ajax request is submitted.

Also you are doing a lot more work then needed to get the selected radio button value (especially since you are using jQuery).

You can replace...

var radio_check_val=0;

for (i = 0; i < document.getElementsByName('radio').length; i++) {
    if (document.getElementsByName('radio')[i].checked) {
        radio_check_val = document.getElementsByName('radio')[i].value;
    }
}

with something similar to....

var radio_check_val = $('radio').filter(':checked').val(); 
//this will only work if there is only one set of radio buttons on the page.
//Otherwise you will need to add a name to the selector.
Jared
  • 5,840
  • 5
  • 49
  • 83
  • Which in this case Ajax function should be? – Kot Fantazer Oct 08 '12 at 20:37
  • I don't understand the question can you elaborate? – Jared Oct 08 '12 at 20:39
  • The first block of my code: – Kot Fantazer Oct 08 '12 at 20:49
  • Help me, please! How to make AJAX request for multiple forms or controllers? – Kot Fantazer Nov 13 '12 at 13:25
  • Please don't take this wrong, but I have little desire to continue putting time into answering a question when the asker can't accept an answer from someone or upvote them if it helped.... – Jared Nov 18 '12 at 04:11
  • 1
    @KotFantazer if this worked then mark the answer as the one that solved your problem (this holds true for any question you ask). Also if you piece together a solution from multiple responses then be sure to upvote all the ones that helped you as well as marking the "MOST" helpful one as a solution. – Jared Nov 19 '12 at 21:25
-1

You should not RedirectToAction. Instead of redirect return PartialView('Registration');.

Related questions:
MVC Return Partial View as JSON.
Load PartialView for AJAX and View for non-AJAX request

Community
  • 1
  • 1
Anatolii Gabuza
  • 6,184
  • 2
  • 36
  • 54
  • Downvoted as it's a [link-only answer](https://meta.stackexchange.com/a/8259/171858). This answer provide no *actual answer*. – Erik Philips Dec 19 '17 at 02:43
  • @ErikPhilips the answer back in 2012 was to use `PartialView` instead of `RedirectToAction`. How is that link-only answer? – Anatolii Gabuza Jan 07 '18 at 17:42