15 October 2015

Using Chart.js with MVC



This is how the view might look

 @model wapitest.Models.ChartData  
 <!doctype html>  
 @{  
   ViewBag.Title = "Index";  
   Layout = null;  
 }  
 <html>  
 <head>  
   <title>Line Chart</title>  
   <script src="~/Scripts/Chart.js"></script>  
 </head>  
 <body>  
   @Model.title  
   <div style="width:30%">  
     <div>  
       <canvas id="canvas" height="450" width="600"></canvas>  
     </div>  
   </div>  
   <script>  
           var lineChartData = {  
             labels : @Html.Raw(Model.label) ,  
                datasets : [  
                     {  
                          label: "D1",  
                          fillColor : "rgba(220,220,220,0.2)",  
                          strokeColor : "rgba(220,220,220,1)",  
                          pointColor : "rgba(220,220,220,1)",  
                          pointStrokeColor : "#fff",  
                          pointHighlightFill : "#fff",  
                          pointHighlightStroke : "rgba(220,220,220,1)",  
                          data : @Model.data  
                     },  
                     {  
                          label: "D2",  
                          fillColor : "rgba(151,187,205,0.2)",  
                          strokeColor : "rgba(151,187,205,1)",  
                          pointColor : "rgba(151,187,205,1)",  
                          pointStrokeColor : "#fff",  
                          pointHighlightFill : "#fff",  
                          pointHighlightStroke : "rgba(151,187,205,1)",  
                          data : [7,6,5,4,3,2,1]  
                     }  
                ]  
           }  
      window.onload = function(){  
           var ctx = document.getElementById("canvas").getContext("2d");  
           window.myLine = new Chart(ctx).Line(lineChartData, {  
                responsive: true  
           });  
      }  
   </script>  
 </body>  
 </html>  


This is the model

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace wapitest.Models  
 {  
   public class ChartData  
   {  
     public string label { get; set; }  
     public string data { get; set; }  
     public string title { get; set; }  
   }  
 }  


And this is the controller function

     public ActionResult Chart()  
     {  
       ViewBag.Title = "Line chart";  
       ChartData cd = new ChartData();  
       cd.title = "Chart Title";  
       cd.data = "[1,5,10,15,5,4,3]";  
       cd.label = @"[""mon"", ""tue"", ""wed"", ""thu"", ""fri"", ""sat"", ""sun""]";  
       return View(cd);  
     }  

12 October 2015

How to do inline css

 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>Welcome to our survey</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
   <STYLE type="text/css">  
     body{  
       font-family:Verdana,Arial,sans-serif;  
       font-size:0.8em;  
     }  
     .QuestionLabel {  
       left:10em;  
       position:relative  
     }  
     .AnswerInput{  
       left:15em;  
       position:relative  
     }  
   </STYLE>  
 </head>  
 <body>  
   <label for="country" class="QuestionLabel">Select your country: </label>  
   <input id="country" class="AnswerInput">  
   <br />  

Posting data in MVC example

Here is the view

 <!doctype html>  
 @{  
   ViewBag.Title = "Index";  
   Layout = null;  
 }  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>Save City</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
 </head>  
 <body>  
   <label for="country">Select your country: </label>  
   <input id="country">  
   <br />  
   <label for="city">Select your city: </label>  
   <input id="city">  
   <br />  
   <input type="button" name="btnclick" id="btnclick" value="click" />  
   <div id="divAlert"> </div>  
   <script>  
     $('#btnclick').click(function () {  
     $.ajax({  
       url: '@Url.Action("InsertCity", "Home")',  
       type: 'POST',  
       data: JSON.stringify({ countryName: $('#country').val(), city: $('#city').val() }),  
       contentType: 'application/json; charset=utf-8',  
       dataType: 'json',  
       success: function (rdata) {  
         $('#divAlert').html(rdata.result);  
       },  
       error: function (req, status, error) {  
         alert("R: " + req + " S: " + status + " E: " + error);  
       }  
     });  
   })  
   </script>  
 </body>  
 </html>  


Here is the controller function

     [HttpPost]  
     public JsonResult InsertCity(string countryName, string city)  
     {  
       string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;  
       SqlConnection dcnn = new SqlConnection(cnnStr);  
       dcnn.Open();  
       SqlCommand dcmd = new SqlCommand("dbo.InsertCity", dcnn);  
       dcmd.CommandType = CommandType.StoredProcedure;  
       dcmd.Parameters.AddWithValue("@CountryName", countryName);  
       dcmd.Parameters.AddWithValue("@City", city);  
       SqlParameter dRet = new SqlParameter("@ReturnValue", SqlDbType.Int, 4);  
       dRet.Direction = ParameterDirection.ReturnValue;  
       dcmd.Parameters.Add(dRet);  
       dcmd.ExecuteNonQuery();  
       int iRet = Utility.ConvertToInt(dRet.Value);  
       return Json(new { result = "successfully submitted" }, JsonRequestBehavior.AllowGet);  
     }  



08 October 2015

How to create autocomplete text box in MVC

Here is the View page, notice I include jquery-ui.css, jquery-1.10.2.js and jquery-ui.js and I am calling the FindCountry function from the controller

 <!doctype html>  
 @{  
   ViewBag.Title = "I2";  
   Layout = null;  
 }  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>autocomplete demo</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
 </head>  
 <body>  
   <label for="country">Select your country: </label>  
   <input id="country">  
   <script>  
     $("#country").autocomplete({  
       source: function (request, response) {  
         var item = new Array();  
         $.ajax({  
           async: false,  
           cache: false,  
           type: "POST",  
           url: "@(Url.Action("FindCountry", "Home"))",  
           data: { "term": request.term },  
         success: function (data) {  
           for (var i = 0; i < data.length ; i++) {  
             item[i] = { label: data[i].Value, Id: data[i].Key };  
           }  
         }  
         });  
         response(item);  
       },  
     });  
   </script>  
 </body>  
 </html>  


and here is the function in the controller

     [AcceptVerbs(HttpVerbs.Post)]  
     public JsonResult FindCountry(string term)  
     {  
       string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;  
       SqlConnection dcnn = new SqlConnection(cnnStr);  
       SqlCommand dcmd = new SqlCommand("dbo.FindCountry", dcnn);  
       dcmd.CommandType = CommandType.StoredProcedure;  
       dcmd.Parameters.AddWithValue("@Term", term);  
       SqlDataAdapter da = new SqlDataAdapter();  
       da.SelectCommand = dcmd;  
       DataSet ds = new DataSet();  
       da.Fill(ds);  
       List<KeyValuePair<string, string>> cty = ds.Tables[0].AsEnumerable().Select(row => new KeyValuePair<string, string>((string)row["CountryCode"], (string)row["CountryName"])).ToList();  
       return Json(cty, JsonRequestBehavior.AllowGet);  
     }