Click here to Skip to main content
15,887,892 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have highchart(pie chart) webapplication.Now i want to convert into MVC how to do it?
here iam used webservices and ajax jquery mehod.

What I have tried:

Webservice
C#
[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class city : System.Web.Services.WebService
    {

        public class cityPopulation
        {
            public string city_name { get; set; }
            public int population { get; set; }
            public string id { get; set; }
        }
        [WebMethod]
        public List<cityPopulation> getCityPopulation(List<string> pData)
        {
            List<cityPopulation> p = new List<cityPopulation>();

            using ( SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
            {
                string myQuery = "SELECT id,city_name,population FROM  citypopulation WHERE  year = @year";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = myQuery;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@year", pData[0]);
                cmd.Connection = cn;
                cn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        cityPopulation cpData = new cityPopulation();
                        cpData.city_name = dr["city_name"].ToString();
                        cpData.population = Convert.ToInt32(dr["population"].ToString());
                        p.Add(cpData);
                    }
                }
            }
            return p;
        }

    }

}


Jquery In aspx page
JavaScript
<script type="text/javascript">
    $(document).ready(function() {

        $("#btnCreatePieChart").on('click', function(e) {
            debugger;
            var pData = [];
            pData[0] = $("#ddlyear").val();

            var jsonData = JSON.stringify({ pData: pData });

            $.ajax({
                type: "POST",
                url: "city.asmx/getCityPopulation",
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess_,
                error: OnErrorCall_
            });

            function OnSuccess_(response) {
                debugger;
                var aData = response.d;
                var arr = []

                $.map(aData, function(item, index) {
                    var i = [item.city_name, item.population];
                    var obj = {};
                    obj.name = item.city_name;
                    obj.y = item.population;
                    arr.push(obj);
                });
                var myJsonString = JSON.stringify(arr);
                var jsonArray = JSON.parse(JSON.stringify(arr));

                drawPieChart(jsonArray);

            }
            function OnErrorCall_(response) {
                alert("Whoops something went wrong!");
            }
            e.preventDefault();
        });

    });
    

        
            function drawPieChart(seriesData) {
                
                $('#container').highcharts({
                
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false,
                        type: 'pie'
                    },
                    title: {
                        text: 'Population city wise'
                    },
                    tooltip: {
                        pointFormat: '{series.name}: {point.percentage:.1f}%'
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                format: '{point.name}: {point.percentage:.1f} %',
                                style: {
                                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                }
                            }
                        }
                    },
                    series: [{
                        name: "Brands",
                        colorByPoint: true,
                        data: seriesData
}]
                    });
                }
            

    
    </script>
Posted
Updated 4-May-17 23:21pm
Comments
F-ES Sitecore 5-May-17 5:39am    
Learn MVC and how to convert your code will become clear, this is not a code-to-order site where people do your work for you. As you're using webmethods and mainly js to do the work it shouldn't be too hard to convert, just use an Action rather than a webmethod.

1 solution

1. First you have to create project with MVC pattern then it will create folders from that you can find Controller, Model, View folders.
2. Add your cityPopulation class in side model folder with your list of properties.
3. Create one controller in side controller folder and name it as per your req.
3. Crate a view inside a view folder and name it as your your choice.

From this view put your ajax call.:
script type="text/javascript">
    $(document).ready(function() {
 
        $("#btnCreatePieChart").on('click', function(e) {
            debugger;
            var pData = [];
            pData[0] = $("#ddlyear").val();
 
            var jsonData = JSON.stringify({ pData: pData });
 
            $.ajax({
                type: "POST",
                url: "YourControllerName/getCityPopulation",
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess_,
                error: OnErrorCall_
            });
 
            function OnSuccess_(response) {
                debugger;
                var aData = response.d;
                var arr = []
 
                $.map(aData, function(item, index) {
                    var i = [item.city_name, item.population];
                    var obj = {};
                    obj.name = item.city_name;
                    obj.y = item.population;
                    arr.push(obj);
                });
                var myJsonString = JSON.stringify(arr);
                var jsonArray = JSON.parse(JSON.stringify(arr));
 
                drawPieChart(jsonArray);
 
            }
            function OnErrorCall_(response) {
                alert("Whoops something went wrong!");
            }
            e.preventDefault();
        });
 
    });
    
 
        
            function drawPieChart(seriesData) {
                
                $('#container').highcharts({
                
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false,
                        type: 'pie'
                    },
                    title: {
                        text: 'Population city wise'
                    },
                    tooltip: {
                        pointFormat: '{series.name}: {point.percentage:.1f}%'
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                format: '{point.name}: {point.percentage:.1f} %',
                                style: {
                                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                }
                            }
                        }
                    },
                    series: [{
                        name: "Brands",
                        colorByPoint: true,
                        data: seriesData
}]
                    });
                }

----------------------------------------
Inside controller create one action method :

public List<cityPopulation> getCityPopulation(List<string> pData)
        {
            List<cityPopulation> p = new List<cityPopulation>();
 
            using ( SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
            {
                string myQuery = "SELECT id,city_name,population FROM  citypopulation WHERE  year = @year";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = myQuery;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@year", pData[0]);
                cmd.Connection = cn;
                cn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        cityPopulation cpData = new cityPopulation();
                        cpData.city_name = dr["city_name"].ToString();
                        cpData.population = Convert.ToInt32(dr["population"].ToString());
                        p.Add(cpData);
                    }
                }
            }
            return p;
        }
 
    }


-----------------

Check this it may help you.
 
Share this answer
 
Comments
GrpSMK 5-May-17 6:02am    
thank you,do you know how to call webservice in mvc?
Ramesh Kumar Barik 5-May-17 6:07am    
Refer this link u can get better idea.
http://www.c-sharpcorner.com/UploadFile/653eb2/consuming-web-services-in-Asp-Net-mvc-5-application/
GrpSMK 5-May-17 7:19am    
inside action the webservice code is enough?
Ramesh Kumar Barik 5-May-17 8:47am    
Yes..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900