使用获取的Json数据在Ajax成功调用中返回部分视图 [英] Return Partial View in Ajax Success Call with Fetched Json Data

查看:130
本文介绍了使用获取的Json数据在Ajax成功调用中返回部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过AJAX调用获取JSON数据到ASP.NET MVC项目中的控制器.我可以从Web API调用中获取JSON数据.现在,我想将返回到我的AJAX调用中success函数的JSON数据并将其传递到局部视图,而不是使用jQuery静态附加JSON数据.

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#控制器:

[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);

    }

编辑:我在下面创建了一个新模型 CompanyResultsModel:

I created a new model below CompanyResultsModel:

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

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

        }


    }
});

我尝试遵循几种在控制器内创建模型的方法来追加此JSON数据,但我不确定这是否是最佳方法.

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.

任何帮助将不胜感激!

推荐答案

编辑AJAX部分后,我认为我发现了一种更简单的方法来完成您要完成的任务.

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

您将希望控制器返回PartialViewResult,以便将HTML传达到您的前端:

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

}

请注意Controller方法的Return Type.

Note the Return Type of the Controller method.

然后可以将在AJAX success函数中使用的for loop移到_CompanyFinderResults.cshtml中,然后让MVC View Engine为您执行该处理.

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函数以处理返回的PartialViewData:

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

因此,我相信您可以在此处选择3种方法:

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

1..您可以让AJAX调用触发第二个AJAX调用,以检索PartialView来更新HTML中的div.

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

2..您可以让现有的AJAX调用返回PartialView来更新HTML中的div.

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

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

我建议第二种选择,这是我的答案所针对的.它似乎是实现目标的最有效解决方案.

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

我不建议使用第三个选项,因为它将需要很多string concatenation,这将是非常难以管理的代码.但是,由于您不必像其他选择中那样与MVC framework进行交互,因此开发起来会更容易.

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.

这篇关于使用获取的Json数据在Ajax成功调用中返回部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆