简体   繁体   English

使用获取的Json数据在Ajax成功调用中返回部分视图

[英]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. 我通过对ASP.NET MVC项目中的控制器的AJAX调用获取JSON数据。 I am able to get the JSON data from the Web API call just fine. 我可以从Web API调用中获取JSON数据。 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. 现在,我想将返回到我的AJAX调用中的success函数的JSON数据并将其传递到局部视图,而不是使用jQuery静态附加JSON数据。

C# Controller: C#控制器:

[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: 编辑:我在CompanyResultsModel:下面创建了一个新模型CompanyResultsModel:

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

AJAX Call: AJAX电话:

$.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. 我尝试遵循几种在控制器中创建模型以追加此JSON数据的方法,但是我不确定这是否是最佳方法。

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. 编辑完AJAX部分后,我想我会发现一种更简单的方法来完成您要完成的任务。

You'll want your controller to return a PartialViewResult so that HTML is communicated to your front end: 您将希望控制器返回PartialViewResult以便将HTML传达到您的前端:

[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. 注意控制器方法的Return Type

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. 然后,您可以将AJAX success函数中使用的for loop移到_CompanyFinderResults.cshtml然后让MVC View Engine为您执行该处理。

Then adjust your AJAX success function to handle the returned PartialViewData : 然后调整您的AJAX success函数以处理返回的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: 编辑:所以我相信您在这里有3种选择:

1. You can have your AJAX call trigger a second AJAX call to retrieve a PartialView to update a div in your HTML. 1.您可以让AJAX调用触发第二个AJAX调用,以检索PartialView来更新HTML中的div

2. You can have your existing AJAX call return a PartialView to update a div in your HTML. 2.您可以让现有的AJAX调用返回PartialView来更新HTML中的div

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. 3.您可以在AJAX调用的success function中编写JavaScript,以构建所需的HTML,以更新HTML中的div

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. 我不建议使用第三个选项,因为它将需要大量的string concatenation ,这将是非常难以管理的代码。 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. 但是,由于不必像其他选择那样与MVC framework进行交互,因此开发起来会更容易。

I can show you how to do any of these solutions if you would like. 如果您愿意,我可以向您展示如何执行这些解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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