Перезагрузка MVC Частичное представление - PullRequest
0 голосов
/ 26 февраля 2019

Хорошо, поэтому у меня есть частичное представление визуализации (раздел d3).Данные и детали заполняются в частичном представлении через файл .js, который обновляется с помощью ac # backend, который извлекает данные из базы данных sql и помещает их в правильный формат.

Моя проблема в том, что я хотел бы заполнить этот раздел различными результатами (по странам) в зависимости от выбора, сделанного пользователем на главной странице.

Я поигрался с событиями ajax и onchange, чтобы вызвать бэкэнд-код населения.Это работает, однако я считаю, что моя проблема в том, что я пишу в файл .js, который заполняет частичное представление.я пишу в локальную папку \ source \ repos \ MVC \ scripts ....Как только экземпляр MVC загружен на веб-сайт, я полагаю, что единственный способ изменить частичное представление с помощью этого метода - обновить всю страницу.

Я хотел бы знать, есть ли способ написать в размещенный файл .js и позволить коду ajax обновить визуализацию обновленной информацией.

Главный вид

<table class="tg">
<tr>
    <td class="tg-0lax">@Html.Partial("SPPDVis1")</td>

    <td class="tg-0lax">@Html.Partial("SPPDVis2")</td>
</tr>
<tr>
    <td class="tg-0lax">@Html.Partial("SPPDVis3")</td>

    <td class="tg-0lax">@Html.Partial("SPPDVis4")</td>


</tr>
<tr>
    <td id="DataPartition" class="tg-0lax">

        @Html.DropDownList("Partitionbox", Model.Countries, "Select Country")

        <button id="button1" type="submit" class="btn btn-primary">Get Data</button>



        <script type="text/javascript">
        jQuery(document).ready(function () {
            $("#Partitionbox").change(function () {
                var id = $(this).find(":selected").text()
                var selectid = { "id": id }

                $.ajax({
                    url: '@Url.Action("RefreshView")',
                    data: JSON.stringify(selectid),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        // Variable data contains the data you get from the action method
                        $('#DPartition').load(data);

                    },


                });
            });
        });
        </script>
        <div id="DPartition">
            @{Html.RenderPartial("DataPartition");}

        </div>

    </td>
</tr>

Частичное представление DataPartition

    @model sb_admin_2.Web.Models.CWCountriesISOandCoordinates_MemberModel

@{ 
   // sb_admin_2.Web.ContentBuilder.PartitionBuilder.TradeVisual("Export", "Barbados", "X2015");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>


<div id="Partition">
    <div id="top">
      

    </div>
    <div id="footer">

        <div class="hint"></div>
    </div>
</div>


<script type="text/javascript">
    var w = 600,
        h = 400,
        x = d3.scale.linear().range([0, w]),
        y = d3.scale.linear().range([0, h]);
    var vis = d3.select("#top").append("div")
        .attr("class", "chart")
        .style("width", w + "px")
        .style("height", h + "px")
        .append("svg:svg")
        .attr("width", w)
        .attr("height", h);
    var partition = d3.layout.partition()
        .value(function (d) {
            return d.size;
        });

    data = flare;

    createchart(data);

    function refreshview() {
        setInterval(function () { $('#contributors').load('/Home/GetContributor'); }, 10000); // every 3 sec
    };

    function createchart(root) {
        var g = vis.selectAll("g")
            .data(partition.nodes(root))
            .enter().append("svg:g")
            .attr("transform", function (d) { return "translate(" + x(d.y) + "," + y(d.x) + ")"; })
            .on("click", click);
        var kx = w / root.dx,
            ky = h / 1;
        g.append("svg:rect")
            .attr("width", root.dy * kx)
            .attr("height", function (d) { return d.dx * ky; })
            .attr("class", function (d) { return d.children ? "parent" : "child"; });
        g.append("svg:text")
            .attr("transform", transform)
            .attr("dy", ".35em")
            .style("opacity", function (d) { return d.dx * ky > 12 ? 1 : 0; })
            .text(function (d) { return d.name + ": $" + d.size; })
        d3.select(window)
            .on("click", function () { click(root); })
        function click(d) {
            if (!d.children) return;
            kx = (d.y ? w - 40 : w) / (1 - d.y);
            ky = h / d.dx;
            x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
            y.domain([d.x, d.x + d.dx]);
            var t = g.transition()
                .duration(d3.event.altKey ? 7500 : 750)
                .attr("transform", function (d) { return "translate(" + x(d.y) + "," + y(d.x) + ")"; });
            t.select("rect")
                .attr("width", d.dy * kx)
                .attr("height", function (d) { return d.dx * ky; });
            t.select("text")
                .attr("transform", transform)
                .style("opacity", function (d) { return d.dx * ky > 12 ? 1 : 0; });
            d3.event.stopPropagation();
        }
        function transform(d) {
            return "translate(8," + d.dx * ky / 2 + ")";
        }
    };

    document.getElementById('footer').append(footer);
    var ele = document.createElement("div");
    ele.classList.add("hint");
    ele.append(hint);
    document.getElementById('footer').appendChild(ele);
</script>

Контроллер

[HttpPost]
    public ActionResult RefreshView(string id)
    {
        sb_admin_2.Web.ContentBuilder.PartitionBuilder.TradeVisual("Export", id, "X2015");

        return PartialView("DataPartition");
    }

.jS Файл данных

footer="Grenada Export -X2015 (US$ 000)"; 
hint="click or option-click to descend or ascend"; 
flare={"name": "Grenada", "size":33.198, "children": [ { "name": "Anguilla", "size": 8.225, "children": [  { "name": "    Food and live animals", "size": 0.028},  { "name": "    Beverages and tobacco", "size": 0.057},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.191},  { "name": "    Miscellaneous manufactured articles", "size": 7.949}  ]}, { "name": "Argentina", "size": 35.374, "children": [  { "name": "    Food and live animals", "size": 33.882},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.805},  { "name": "    Manufactured goods", "size": 0.214},  { "name": "    Machinery and transport equipment", "size": 0.106},  { "name": "    Miscellaneous manufactured articles", "size": 0.367}  ]}, { "name": "Aruba", "size": 3.146, "children": [  { "name": "    Crude materials, inedible, except fuels", "size": 0.005},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.348},  { "name": "    Miscellaneous manufactured articles", "size": 2.793}  ]}, { "name": "Austria", "size": 212.031, "children": [  { "name": "    Food and live animals", "size": 211.925},  { "name": "    Beverages and tobacco", "size": 0.017},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.04},  { "name": "    Miscellaneous manufactured articles", "size": 0.049}  ]}, { "name": "Belgium", "size": 464.37, "children": [  { "name": "    Food and live animals", "size": 435.776},  { "name": "    Mineral fuels, lubricants and related materials", "size": 0.049},  { "name": "    Animal and vegetable oils, fats and waxes", "size": 26.749},  { "name": "    Machinery and transport equipment", "size": 1.796},  { "name": "    Miscellaneous manufactured articles", "size": 0.001}  ]}, { "name": "Bermuda", "size": 1.536, "children": [  { "name": "    Chemicals and related products, n.e.s.", "size": 0.41},  { "name": "    Manufactured goods", "size": 0.366},  { "name": "    Machinery and transport equipment", "size": 0.082},  { "name": "    Miscellaneous manufactured articles", "size": 0.678}  ]}, { "name": "British Virgin Islands", "size": 3.11, "children": [  { "name": "    Food and live animals", "size": 0.92},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.128},  { "name": "    Manufactured goods", "size": 0.103},  { "name": "    Machinery and transport equipment", "size": 1.922},  { "name": "    Miscellaneous manufactured articles", "size": 0.037}  ]}, { "name": "Cayman Islands", "size": 1.383, "children": [  { "name": "    Food and live animals", "size": 0.066},  { "name": "    Crude materials, inedible, except fuels", "size": 0.004},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.018},  { "name": "    Manufactured goods", "size": 0.012},  { "name": "    Miscellaneous manufactured articles", "size": 1.282}  ]}, { "name": "China", "size": 65.715, "children": [  { "name": "    Food and live animals", "size": 0.483},  { "name": "    Crude materials, inedible, except fuels", "size": 5.057},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.559},  { "name": "    Manufactured goods", "size": 8.965},  { "name": "    Machinery and transport equipment", "size": 17.909},  { "name": "    Miscellaneous manufactured articles", "size": 32.742}  ]}, { "name": "China, Hong Kong SAR", "size": 1.246, "children": [  ]}, { "name": "China, Taiwan Province of", "size": 200.828, "children": [  { "name": "    Beverages and tobacco", "size": 0.157},  { "name": "    Crude materials, inedible, except fuels", "size": 63.856},  { "name": "    Manufactured goods", "size": 62.459},  { "name": "    Machinery and transport equipment", "size": 1.572},  { "name": "    Miscellaneous manufactured articles", "size": 72.783}  ]}, { "name": "Colombia", "size": 3.484, "children": [  { "name": "    Manufactured goods", "size": 0.004},  { "name": "    Machinery and transport equipment", "size": 0.035},  { "name": "    Miscellaneous manufactured articles", "size": 3.445}  ]}, { "name": "Costa Rica", "size": 6.182, "children": [  { "name": "    Manufactured goods", "size": 3.143},  { "name": "    Machinery and transport equipment", "size": 2.161},  { "name": "    Miscellaneous manufactured articles", "size": 0.878}  ]}, { "name": "Croatia", "size": 30.973, "children": [  { "name": "    Food and live animals", "size": 16.729},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.349},  { "name": "    Manufactured goods", "size": 13.793},  { "name": "    Machinery and transport equipment", "size": 0.043},  { "name": "    Miscellaneous manufactured articles", "size": 0.059}  ]}, { "name": "Curaçao", "size": 28.35, "children": [  { "name": "    Food and live animals", "size": 2.972},  { "name": "    Beverages and tobacco", "size": 0.001},  { "name": "    Crude materials, inedible, except fuels", "size": 0.006},  { "name": "    Mineral fuels, lubricants and related materials", "size": 1.15},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.268},  { "name": "    Manufactured goods", "size": 1.812},  { "name": "    Machinery and transport equipment", "size": 19.661},  { "name": "    Miscellaneous manufactured articles", "size": 2.481}  ]}, { "name": "Denmark", "size": 1.727, "children": [  { "name": "    Food and live animals", "size": 0.077},  { "name": "    Beverages and tobacco", "size": 0.036},  { "name": "    Manufactured goods", "size": 0.047},  { "name": "    Miscellaneous manufactured articles", "size": 1.568}  ]}, { "name": "Dominican Republic", "size": 279.041, "children": [  { "name": "    Food and live animals", "size": 44.492},  { "name": "    Crude materials, inedible, except fuels", "size": 0.809},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.401},  { "name": "    Manufactured goods", "size": 65.852},  { "name": "    Machinery and transport equipment", "size": 144.16},  { "name": "    Miscellaneous manufactured articles", "size": 23.326}  ]}, { "name": "Faeroe Islands", "size": 0.467, "children": [  { "name": "    Food and live animals", "size": 0.467}  ]}, { "name": "Finland", "size": 39.29, "children": [  { "name": "    Food and live animals", "size": 11.399},  { "name": "    Crude materials, inedible, except fuels", "size": 0.485},  { "name": "    Manufactured goods", "size": 13.334},  { "name": "    Machinery and transport equipment", "size": 9.751},  { "name": "    Miscellaneous manufactured articles", "size": 4.321}  ]}, { "name": "France", "size": 1643.027, "children": [  { "name": "    Food and live animals", "size": 403.933},  { "name": "    Beverages and tobacco", "size": 0.065},  { "name": "    Crude materials, inedible, except fuels", "size": 6.879},  { "name": "    Chemicals and related products, n.e.s.", "size": 75.026},  { "name": "    Manufactured goods", "size": 584.388},  { "name": "    Machinery and transport equipment", "size": 530.547},  { "name": "    Miscellaneous manufactured articles", "size": 42.189}  ]}, { "name": "Germany", "size": 765.818, "children": [  { "name": "    Food and live animals", "size": 570.267},  { "name": "    Beverages and tobacco", "size": 0.122},  { "name": "    Mineral fuels, lubricants and related materials", "size": 0.651},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.796},  { "name": "    Manufactured goods", "size": 18.166},  { "name": "    Machinery and transport equipment", "size": 173.28},  { "name": "    Miscellaneous manufactured articles", "size": 2.537}  ]}, { "name": "Indonesia", "size": 28.348, "children": [  { "name": "    Crude materials, inedible, except fuels", "size": 1.229},  { "name": "    Chemicals and related products, n.e.s.", "size": 10.524},  { "name": "    Manufactured goods", "size": 15.761},  { "name": "    Machinery and transport equipment", "size": 0.833}  ]}, { "name": "Ireland", "size": 34.359, "children": [  { "name": "    Food and live animals", "size": 1.553},  { "name": "    Beverages and tobacco", "size": 0.067},  { "name": "    Chemicals and related products, n.e.s.", "size": 7.719},  { "name": "    Manufactured goods", "size": 10.614},  { "name": "    Machinery and transport equipment", "size": 6.124},  { "name": "    Miscellaneous manufactured articles", "size": 8.282}  ]}, { "name": "Italy", "size": 228.44, "children": [  { "name": "    Food and live animals", "size": 17.395},  { "name": "    Beverages and tobacco", "size": 0.63},  { "name": "    Manufactured goods", "size": 0.367},  { "name": "    Machinery and transport equipment", "size": 210.048}  ]}, { "name": "Japan", "size": 1270.124, "children": [  { "name": "    Food and live animals", "size": 10.116},  { "name": "    Beverages and tobacco", "size": 2.575},  { "name": "    Crude materials, inedible, except fuels", "size": 10.826},  { "name": "    Manufactured goods", "size": 1.239},  { "name": "    Machinery and transport equipment", "size": 1196.935},  { "name": "    Miscellaneous manufactured articles", "size": 48.434}  ]}, { "name": "Kazakhstan", "size": 2.718, "children": [  { "name": "    Machinery and transport equipment", "size": 1.951},  { "name": "    Miscellaneous manufactured articles", "size": 0.767}  ]}, { "name": "Korea, Republic of", "size": 44.818, "children": [  { "name": "    Crude materials, inedible, except fuels", "size": 4.255},  { "name": "    Mineral fuels, lubricants and related materials", "size": 0.489},  { "name": "    Chemicals and related products, n.e.s.", "size": 2.286},  { "name": "    Manufactured goods", "size": 5.457},  { "name": "    Machinery and transport equipment", "size": 31.492},  { "name": "    Miscellaneous manufactured articles", "size": 0.839}  ]}, { "name": "Montenegro", "size": 15.437, "children": [  { "name": "    Food and live animals", "size": 2.021},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.066},  { "name": "    Manufactured goods", "size": 2.235},  { "name": "    Machinery and transport equipment", "size": 10.701},  { "name": "    Miscellaneous manufactured articles", "size": 0.414}  ]}, { "name": "Montserrat", "size": 82.539, "children": [  { "name": "    Food and live animals", "size": 80.064},  { "name": "    Chemicals and related products, n.e.s.", "size": 1.587},  { "name": "    Manufactured goods", "size": 0.887}  ]}, { "name": "Netherlands", "size": 942.759, "children": [  { "name": "    Food and live animals", "size": 839.112},  { "name": "    Beverages and tobacco", "size": 6.453},  { "name": "    Crude materials, inedible, except fuels", "size": 4.143},  { "name": "    Manufactured goods", "size": 7.799},  { "name": "    Machinery and transport equipment", "size": 77.175},  { "name": "    Miscellaneous manufactured articles", "size": 8.076}  ]}, { "name": "Norway", "size": 84.922, "children": [  { "name": "    Food and live animals", "size": 84.613},  { "name": "    Machinery and transport equipment", "size": 0.309}  ]}, { "name": "Peru", "size": 0.876, "children": [  { "name": "    Manufactured goods", "size": 0.867},  { "name": "    Machinery and transport equipment", "size": 0.01}  ]}, { "name": "Suriname", "size": 46.438, "children": [  { "name": "    Food and live animals", "size": 2.332},  { "name": "    Chemicals and related products, n.e.s.", "size": 3.032},  { "name": "    Manufactured goods", "size": 27.275},  { "name": "    Machinery and transport equipment", "size": 13.799}  ]}, { "name": "Sweden", "size": 4.298, "children": [  { "name": "    Chemicals and related products, n.e.s.", "size": 0.336},  { "name": "    Machinery and transport equipment", "size": 3.896},  { "name": "    Miscellaneous manufactured articles", "size": 0.066}  ]}, { "name": "Switzerland", "size": 138.597, "children": [  { "name": "    Food and live animals", "size": 122.571},  { "name": "    Beverages and tobacco", "size": 0.026},  { "name": "    Crude materials, inedible, except fuels", "size": 1.154},  { "name": "    Animal and vegetable oils, fats and waxes", "size": 1.151},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.883},  { "name": "    Machinery and transport equipment", "size": 6.648},  { "name": "    Miscellaneous manufactured articles", "size": 6.164}  ]}, { "name": "Thailand", "size": 191.886, "children": [  { "name": "    Crude materials, inedible, except fuels", "size": 158.009},  { "name": "    Chemicals and related products, n.e.s.", "size": 3.678},  { "name": "    Manufactured goods", "size": 4.867},  { "name": "    Machinery and transport equipment", "size": 25.088},  { "name": "    Miscellaneous manufactured articles", "size": 0.243}  ]}, { "name": "United States", "size": 4486.04, "children": [  { "name": "    Food and live animals", "size": 3383.599},  { "name": "    Beverages and tobacco", "size": 146.579},  { "name": "    Crude materials, inedible, except fuels", "size": 15.454},  { "name": "    Mineral fuels, lubricants and related materials", "size": 4.045},  { "name": "    Animal and vegetable oils, fats and waxes", "size": 3.535},  { "name": "    Chemicals and related products, n.e.s.", "size": 121.356},  { "name": "    Manufactured goods", "size": 67.12},  { "name": "    Machinery and transport equipment", "size": 404.04},  { "name": "    Miscellaneous manufactured articles", "size": 340.311}  ]}, { "name": "Venezuela (Bolivarian Rep. of)", "size": 24.489, "children": [  { "name": "    Chemicals and related products, n.e.s.", "size": 0.004},  { "name": "    Manufactured goods", "size": 0.051},  { "name": "    Machinery and transport equipment", "size": 20.786},  { "name": "    Miscellaneous manufactured articles", "size": 3.648}  ]}, { "name": "Antigua and Barbuda", "size": 616.884, "children": [  { "name": "    Food and live animals", "size": 376.982},  { "name": "    Beverages and tobacco", "size": 9.181},  { "name": "    Crude materials, inedible, except fuels", "size": 0.091},  { "name": "    Mineral fuels, lubricants and related materials", "size": 2.957},  { "name": "    Chemicals and related products, n.e.s.", "size": 2.399},  { "name": "    Manufactured goods", "size": 188.983},  { "name": "    Machinery and transport equipment", "size": 27.906},  { "name": "    Miscellaneous manufactured articles", "size": 8.386}  ]}, { "name": "Bahamas", "size": 10.16, "children": [  { "name": "    Food and live animals", "size": 0.048},  { "name": "    Beverages and tobacco", "size": 0.006},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.178},  { "name": "    Manufactured goods", "size": 3.496},  { "name": "    Miscellaneous manufactured articles", "size": 6.432}  ]}, { "name": "Barbados", "size": 1460.971, "children": [  { "name": "    Food and live animals", "size": 437.987},  { "name": "    Beverages and tobacco", "size": 17.731},  { "name": "    Crude materials, inedible, except fuels", "size": 15.347},  { "name": "    Chemicals and related products, n.e.s.", "size": 23.578},  { "name": "    Manufactured goods", "size": 551.659},  { "name": "    Machinery and transport equipment", "size": 33.519},  { "name": "    Miscellaneous manufactured articles", "size": 381.151}  ]}, { "name": "Canada", "size": 547.263, "children": [  { "name": "    Food and live animals", "size": 491.833},  { "name": "    Beverages and tobacco", "size": 2.532},  { "name": "    Crude materials, inedible, except fuels", "size": 0.005},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.286},  { "name": "    Manufactured goods", "size": 5.096},  { "name": "    Machinery and transport equipment", "size": 42.056},  { "name": "    Miscellaneous manufactured articles", "size": 5.454}  ]}, { "name": "Dominica", "size": 2524.541, "children": [  { "name": "    Food and live animals", "size": 1666.042},  { "name": "    Beverages and tobacco", "size": 0.028},  { "name": "    Crude materials, inedible, except fuels", "size": 0.329},  { "name": "    Chemicals and related products, n.e.s.", "size": 29.094},  { "name": "    Manufactured goods", "size": 448.682},  { "name": "    Machinery and transport equipment", "size": 362.23},  { "name": "    Miscellaneous manufactured articles", "size": 18.135}  ]}, { "name": "Guyana", "size": 367.196, "children": [  { "name": "    Food and live animals", "size": 6.167},  { "name": "    Beverages and tobacco", "size": 24.546},  { "name": "    Crude materials, inedible, except fuels", "size": 9.323},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.909},  { "name": "    Manufactured goods", "size": 321.509},  { "name": "    Machinery and transport equipment", "size": 4.321},  { "name": "    Miscellaneous manufactured articles", "size": 0.421}  ]}, { "name": "India", "size": 25.976, "children": [  { "name": "    Beverages and tobacco", "size": 5.886},  { "name": "    Crude materials, inedible, except fuels", "size": 3.668},  { "name": "    Chemicals and related products, n.e.s.", "size": 1.769},  { "name": "    Manufactured goods", "size": 1.623},  { "name": "    Machinery and transport equipment", "size": 8.295},  { "name": "    Miscellaneous manufactured articles", "size": 4.736}  ]}, { "name": "Jamaica", "size": 403.284, "children": [  { "name": "    Food and live animals", "size": 162.052},  { "name": "    Beverages and tobacco", "size": 0.004},  { "name": "    Mineral fuels, lubricants and related materials", "size": 1.184},  { "name": "    Chemicals and related products, n.e.s.", "size": 1.241},  { "name": "    Manufactured goods", "size": 228.698},  { "name": "    Machinery and transport equipment", "size": 5.771},  { "name": "    Miscellaneous manufactured articles", "size": 4.333}  ]}, { "name": "Malaysia", "size": 105.211, "children": [  { "name": "    Crude materials, inedible, except fuels", "size": 10.742},  { "name": "    Chemicals and related products, n.e.s.", "size": 2.07},  { "name": "    Manufactured goods", "size": 10.448},  { "name": "    Machinery and transport equipment", "size": 76.402},  { "name": "    Miscellaneous manufactured articles", "size": 5.548}  ]}, { "name": "Nigeria", "size": 8477.15, "children": [  { "name": "    Food and live animals", "size": 627.353},  { "name": "    Crude materials, inedible, except fuels", "size": 399.865},  { "name": "    Chemicals and related products, n.e.s.", "size": 2391.931},  { "name": "    Manufactured goods", "size": 2257.842},  { "name": "    Machinery and transport equipment", "size": 1314.543},  { "name": "    Miscellaneous manufactured articles", "size": 1485.615}  ]}, { "name": "Pakistan", "size": 5.264, "children": [  { "name": "    Beverages and tobacco", "size": 0.031},  { "name": "    Chemicals and related products, n.e.s.", "size": 0.168},  { "name": "    Manufactured goods", "size": 0.314},  { "name": "    Machinery and transport equipment", "size": 4.737},  { "name": "    Miscellaneous manufactured articles", "size": 0.013}  ]}, { "name": "Saint Kitts and Nevis", "size": 1418.357, "children": [  { "name": "    Food and live animals", "size": 1145.933},  { "name": "    Beverages and tobacco", "size": 2.741},  { "name": "    Crude materials, inedible, except fuels", "size": 34.926},  { "name": "    Chemicals and related products, n.e.s.", "size": 15.811},  { "name": "    Manufactured goods", "size": 196.997},  { "name": "    Machinery and transport equipment", "size": 9.149},  { "name": "    Miscellaneous manufactured articles", "size": 12.8}  ]}, { "name": "Saint Lucia", "size": 2051.763, "children": [  { "name": "    Food and live animals", "size": 1233.615},  { "name": "    Beverages and tobacco", "size": 100.57},  { "name": "    Crude materials, inedible, except fuels", "size": 0.095},  { "name": "    Chemicals and related products, n.e.s.", "size": 216.334},  { "name": "    Manufactured goods", "size": 336.26},  { "name": "    Machinery and transport equipment", "size": 153.453},  { "name": "    Miscellaneous manufactured articles", "size": 11.435}  ]}, { "name": "Saint Vincent and the Grenadines", "size": 590.435, "children": [  { "name": "    Food and live animals", "size": 51.824},  { "name": "    Beverages and tobacco", "size": 43.146},  { "name": "    Crude materials, inedible, except fuels", "size": 0.672},  { "name": "    Mineral fuels, lubricants and related materials", "size": 10.454},  { "name": "    Animal and vegetable oils, fats and waxes", "size": 0.413},  { "name": "    Chemicals and related products, n.e.s.", "size": 232.088},  { "name": "    Manufactured goods", "size": 86.194},  { "name": "    Machinery and transport equipment", "size": 85.317},  { "name": "    Miscellaneous manufactured articles", "size": 80.325}  ]}, { "name": "Trinidad and Tobago", "size": 464.045, "children": [  { "name": "    Food and live animals", "size": 207.03},  { "name": "    Beverages and tobacco", "size": 21.538},  { "name": "    Crude materials, inedible, except fuels", "size": 5.583},  { "name": "    Mineral fuels, lubricants and related materials", "size": 3.7},  { "name": "    Chemicals and related products, n.e.s.", "size": 39.11},  { "name": "    Manufactured goods", "size": 20.701},  { "name": "    Machinery and transport equipment", "size": 152.429},  { "name": "    Miscellaneous manufactured articles", "size": 13.954}  ]}, { "name": "Uganda", "size": 8.292, "children": [  { "name": "    Chemicals and related products, n.e.s.", "size": 8.272},  { "name": "    Machinery and transport equipment", "size": 0.02}  ]}, { "name": "United Kingdom", "size": 2009.801, "children": [  { "name": "    Food and live animals", "size": 80.687},  { "name": "    Beverages and tobacco", "size": 32.431},  { "name": "    Crude materials, inedible, except fuels", "size": 0.954},  { "name": "    Chemicals and related products, n.e.s.", "size": 20.647},  { "name": "    Manufactured goods", "size": 13.51},  { "name": "    Machinery and transport equipment", "size": 1832.527},  { "name": "    Miscellaneous manufactured articles", "size": 29.045}  ]}]};

код для заполнения этого файла .js. Я могу получить его строковую версию, если это поможет.

Я знаю, что это немного, но любая помощь будет принята с благодарностью.

EDIT-

string  filepath = @"C:\Users\kr.williams\source\repos\MVCBootstrap\sb-admin-2.Web\Scripts\Partition Data.js";

           // File.WriteAllText(filepath, output);

           // filepath = @"C:\Flask\DataPlatform\templates\Partition\partition.html";
            File.WriteAllText(filepath, html);

Здесь я пишу в файл .js.У меня сильное чувство, что это неправильное место для записи для веб-экземпляра.Это также может быть совершенно неверной реализацией того, что я делаю.

Если я передаю код .js обратно в представление как строку, есть ли способ, с помощью которого я мог бы рассматривать его как код сценария java и извлекать различные возвращаемые переменные?(т.е. нижний колонтитул, подсказка, блик), затем сбросьте эти переменные и перезагрузите представление?

Может кто-нибудь посоветовать мне?

Ответы [ 2 ]

0 голосов
/ 01 марта 2019

После нескольких дней возни, поломки и исправления я нашел решение, которое сработало для меня.

Как указывалось выше, я передал свою строку из функции заполнения данных в действие, а затем в представление с использованием модели.Однако это было не так просто.функция createchart ожидает объект json (мне потребовалось некоторое время, чтобы понять, в чем проблема).передача строки как есть переменной в частичном представлении сделала много ужасных вещей с двойными кавычками и одинарными кавычками, которые были внутри строки.В конце концов я понял, что строку нужно передавать как json, чтобы правильно видеть цитаты в представлении.

Как только это было отсортировано, я просто убирал все, что я сломал, пытаясь выяснить проблему.

Фрагмент частичного просмотра

 var string = JSON.parse(@(Html.Raw(Json.Encode(Model.flare))));

    //data = flare;

    createchart(string);

Фрагмент контроллера

public ActionResult RefreshView(int id)
    {

        CWDataSetsEntities aCWDatasetEntity = new CWDataSetsEntities();

        int intCountryID = Convert.ToInt32(id);

        CWCountriesISOandCoordinates aCWCountry = new CWCountriesISOandCoordinates();

        aCWCountry = (from x in aCWDatasetEntity.CWCountriesISOandCoordinates where x.index == intCountryID select x).SingleOrDefault();
        string Country = aCWCountry.Country_Name;

        Models.PartitionViewModels Data = sb_admin_2.Web.ContentBuilder.PartitionBuilder.TradeVisual("Export", Country, "X2015");

        //sb_admin_2.Web.Models.PartitionViewModels.Javascript = Data;
        ViewBag.Data = Data;

        return PartialView("DataPartition", Data);
    }

Сценарий события

<script>
$(function () {
    $("#Partitionbox").change(function (e) {
        var val = $(this).val();
        $("#DataPart").remove();
        $('#hint').remove();
        $('#footer').remove();
        $("#TestTarget").load("/Home/RefreshView/" + val);
                    });
});
0 голосов
/ 27 февраля 2019

Если у вас есть какие-то особые требования для использования частичного представления, вы можете найти способ перезагрузки в этой статье .Посмотрите на второй ответ, который лучше.

Теперь, предполагая, что вы хотите только заново заполнить диаграмму, почему бы просто не вызвать функцию «createchart» снова после изменения ваших данных в файле .js?Тогда вам вообще не придется использовать частичное представление.

jQuery(document).ready(function() {
  $("#Partitionbox").change(function() {
    var id = $(this).find(":selected").text()
    var selectid = {
      "id": id
    }

    $.ajax({
      url: '@Url.Action("RefreshView")',
      data: JSON.stringify(selectid),
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      success: function(data) {
        // Variable data contains the data you get from the action method
        //$('#DPartition').load(data);

        createchart(data);
      },


    });
  });

  var w = 600,
    h = 400,
    x = d3.scale.linear().range([0, w]),
    y = d3.scale.linear().range([0, h]);
  var vis = d3.select("#top").append("div")
    .attr("class", "chart")
    .style("width", w + "px")
    .style("height", h + "px")
    .append("svg:svg")
    .attr("width", w)
    .attr("height", h);
  var partition = d3.layout.partition()
    .value(function(d) {
      return d.size;
    });

  var data = flare;

  createchart(data);

  function refreshview() {
    setInterval(function() {
      $('#contributors').load('/Home/GetContributor');
    }, 10000); // every 3 sec
  };

  function createchart(root) {
    var g = vis.selectAll("g")
      .data(partition.nodes(root))
      .enter().append("svg:g")
      .attr("transform", function(d) {
        return "translate(" + x(d.y) + "," + y(d.x) + ")";
      })
      .on("click", click);
    var kx = w / root.dx,
      ky = h / 1;
    g.append("svg:rect")
      .attr("width", root.dy * kx)
      .attr("height", function(d) {
        return d.dx * ky;
      })
      .attr("class", function(d) {
        return d.children ? "parent" : "child";
      });
    g.append("svg:text")
      .attr("transform", transform)
      .attr("dy", ".35em")
      .style("opacity", function(d) {
        return d.dx * ky > 12 ? 1 : 0;
      })
      .text(function(d) {
        return d.name + ": $" + d.size;
      })
    d3.select(window)
      .on("click", function() {
        click(root);
      })

    function click(d) {
      if (!d.children) return;
      kx = (d.y ? w - 40 : w) / (1 - d.y);
      ky = h / d.dx;
      x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
      y.domain([d.x, d.x + d.dx]);
      var t = g.transition()
        .duration(d3.event.altKey ? 7500 : 750)
        .attr("transform", function(d) {
          return "translate(" + x(d.y) + "," + y(d.x) + ")";
        });
      t.select("rect")
        .attr("width", d.dy * kx)
        .attr("height", function(d) {
          return d.dx * ky;
        });
      t.select("text")
        .attr("transform", transform)
        .style("opacity", function(d) {
          return d.dx * ky > 12 ? 1 : 0;
        });
      d3.event.stopPropagation();
    }

    function transform(d) {
      return "translate(8," + d.dx * ky / 2 + ")";
    }
  };

  document.getElementById('footer').append(footer);
  var ele = document.createElement("div");
  ele.classList.add("hint");
  ele.append(hint);
  document.getElementById('footer').appendChild(ele);
});
<table class="tg">
  <tr>
    <td class="tg-0lax">@Html.Partial("SPPDVis1")</td>

    <td class="tg-0lax">@Html.Partial("SPPDVis2")</td>
  </tr>
  <tr>
    <td class="tg-0lax">@Html.Partial("SPPDVis3")</td>

    <td class="tg-0lax">@Html.Partial("SPPDVis4")</td>


  </tr>
  <tr>
    <td id="DataPartition" class="tg-0lax">

      @Html.DropDownList("Partitionbox", Model.Countries, "Select Country")

      <button id="button1" type="submit" class="btn btn-primary">Get Data</button>
      <div id="DPartition">
      </div>

    </td>
  </tr>
</table>

Надеюсь, я смогу хоть немного помочь.Удачного кодирования:)

...