Return Partial View in Ajax Success Call with Fetched Json Data

10,776

After editing your AJAX section, I think I see an easier way to do what you're trying to accomplish.

You'll want your controller to return a PartialViewResult so that HTML is communicated to your front end:

[HttpGet]
[Route("company-info/companyinfogetapidata")]
[AllowAnonymous]
public PartialViewResult CompanyInfoGetApiData(string name, int CompanyCode, string city, string state, int zip)
{

    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("URL_BASE");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var request = client.GetAsync("URL_PATH");                
    var json = request.Result.Content.ReadAsStringAsync().Result;

    JObject o = JObject.Parse(json);

    return PartialView(@"_CompanyFinderResults.cshtml", Model);

}

Note the Return Type of the Controller method.

You can then move the for loop you were using in your AJAX success function into your _CompanyFinderResults.cshtml and let the MVC View Engine do that processing for you.

Then adjust your AJAX success function to handle the returned PartialViewData:

     $.ajax({
            type: "GET",
            url:"../companyinfogetapidata",
            dataType: "json",
            data: {DATA HERE},
            error:function(e){alert("nope"+e);},
            success: function (partialViewData) {
                $('#your-div-to-hold-partial-view').html(partialViewData);
            }
        });

Edit: So I believe you have 3 options for an approach here:

1. You can have your AJAX call trigger a second AJAX call to retrieve a PartialView to update a div in your HTML.

2. You can have your existing AJAX call return a PartialView to update a div in your HTML.

3. You can write JavaScript in the success function of your AJAX call to build your desired HTML for updating a div in your HTML.

I recommend the second option, which is what my answer is geared towards. It appears to be the most efficient solution for your goals.

I don't recommend the third option as it will require a lot of string concatenation which will be very unmanageable code. But it will be easier to develop since you won't have to interact with the MVC framework as much as you would in the other options.

I can show you how to do any of these solutions if you would like.

Share:
10,776
Jeff P.
Author by

Jeff P.

Updated on June 04, 2022

Comments

  • Jeff P.
    Jeff P. almost 2 years

    I am fetching JSON data via an AJAX call to a controller within an ASP.NET MVC project. I am able to get the JSON data from the Web API call just fine. Now I want to take this JSON data that is returned to the success function within my AJAX call and pass it to a partial view instead of statically appending JSON data with jQuery.

    C# Controller:

    [HttpGet]
    [Route("company-info/companyinfogetapidata")]
    [AllowAnonymous]
    public ActionResult CompanyInfoGetApiData(string name, int CompanyCode, string city, string state, int zip)
        {
    
            HttpClient client = new HttpClient();
    
            client.BaseAddress = new Uri("URL_BASE");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            var request = client.GetAsync("URL_PATH");                
            var json = request.Result.Content.ReadAsStringAsync().Result;
    
            JObject o = JObject.Parse(json);
    
            JToken ApiData = o["results"];
    
           // Here is where I want to insert pieces of the JSON data into the model and then pass it into the partial view
            CompanyResultsModel getfetcheddata = new CompanyResultsModel();
    
            getfetcheddata = Newtonsoft.Json.JsonConvert.DeserializeObject<CompanyResultsModel>(json);
    
    
            return PartialView(@"~/Views/Shared/companies/_companyResults.cshtml", getfetcheddata);
    
        }
    

    EDIT: I created a new model below CompanyResultsModel:

    namespace Companies.Models
    {
        public class CompanyResultsModel
        {
            public string companyName { get; set; }
        }
    }
    

    AJAX Call:

    $.ajax({
        type: "GET",
        url:"../companyinfogetapidata",
        dataType: "json",
        data: {DATA HERE},
        error:function(e){alert("nope"+e);},
        success: function (xhr_request) {
    
            var fetched_data = xhr_request["results"];
    
            var i;
    
            var iLength = fetched_data.length;
    
            for (i = 0; i < iLength; i++) {
                // This was the original jQuery way I was appending the JSON data
                // $("#CompanyFinderResultsContainer").append("<p>Name:&nbsp;" + fetched_data[i].name + "</p>");
                // I want to call a Partial View and Pass along the JSON data from this success function
                // I am thinking of making a call like this                            
                @Html.Partial("_CompanyFinderResults", Model);
    
            }
    
    
        }
    });
    

    I tried following a few methods of creating a model within the controller to append this JSON data but I'm not quite sure if this is the best approach.

    Any help is greatly appreciated!

  • Jeff P.
    Jeff P. over 6 years
    I'm trying to modify my code but am having issues with the return line return PartialView(@"_CompanyFinderResults.cshtml", Model); where I'm assuming I want to take this JSON data and store it into this Model variable.
  • Luke T Brooks
    Luke T Brooks over 6 years
    So that Model variable should be there model that your PartialView needs to create your View. In your original AJAX section, you had @Html.Partial("_CompanyFinderResults", Model);, this Model variable refers to that one.
  • Jeff P.
    Jeff P. over 6 years
    I wasn't actually using that line of code, it was just a suggestion I had. What I really want to do is take that parsed JSON data from the controller and pass it into the partialView.
  • Luke T Brooks
    Luke T Brooks over 6 years
    Is there a reason that you need the data to get passed back to your JavaScript? It might be more efficient to just process your partial view right after you process your data in your controller.
  • Jeff P.
    Jeff P. over 6 years
    I'm actually really close to getting this to work properly. See my edit above to see what I'm trying to accomplish.
  • Luke T Brooks
    Luke T Brooks over 6 years
    So I think the thing that you are missing is that the @Html.Partial("_CompanyFinderResults", Model); line isn't going to be processed quite how you want. That line is processed before your view loads, it doesn't process when your AJAX call is triggered. To have that line be processed after your AJAX call, you'll need to make a new method on your controller and have a second AJAX call that fires on the success of your first one. If you only want one AJAX call, then you can refer to my posted answer for that solution.
  • Luke T Brooks
    Luke T Brooks over 6 years
    @JeffP. I added an Edit section on my answer with some options for you