简体   繁体   中英

Return Partial View in Ajax Success Call with Fetched Json Data

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM