Sunday, 31 July 2016

Validate Address or Place through google API

<html>
<head>
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&key=Your API Key"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('Address'));
            getLatLong(places);
           
        });

        function placeLastOfFocus()
        {
            // alert(1);
           
           
            // alert(places);
            //document.getElementById('Address').value
            //!a.trim()
            if (!document.getElementById('Address').value.trim()) {
               
                $("#Address1").val('');
                $("#latitude").val('');
                $("#longitude").val('');
                return;
            }
            //doGeocode();
            var places = new google.maps.places.Autocomplete(document.getElementById('Address'));
            getLatLong(places);
        }
        function doGeocode() {
            var addr = document.getElementById("Address");
            // Get geocoder instance
            var geocoder = new google.maps.Geocoder();

            // Geocode the address
            geocoder.geocode({ 'address': addr.value }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK && results.length > 0) {

                    // set it ot he correct, formatted address if it's vadlid
                    addr.value = results[0].formatted_address;;
                    alert("valid");
                    // show an error if it's not
                } else alert("Invalid address");
            });
        };
        function getLatLong(places)
        {
            google.maps.event.addListener(places, 'place_changed', function () {
                $("#Address").val('');
                $("#latitude").val('');
                $("#longitude").val('');
                //alert(1);
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                //var city = place.geometry.location.city();
                //alert(address);
                //for testing purpose alert
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                //alert(mesg);
                $("#Address1").val(address);
                $("#latitude").val(latitude);
                $("#longitude").val(longitude);
            });
        }
    </script>
</head>
<body>                                          
 <textarea name="Address" id="Address" autocomplete="on" class="col-lg-offset-5" ></textarea>
    <input type="text" name="latitude" id="latitude" autocomplete="on" />
    <input type="text" name="longitude" id="longitude" autocomplete="on" />
</body>
</html>

Wednesday, 27 July 2016

MVC Form OnSubmit Client side function calling

html-beginform-using-onsubmit-to-validate

@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, 
new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))

//add javascript function like validateForm(event){//do your code}
<script>
function validateForm(event)
{
//do your code
}
</script>

Thursday, 21 July 2016

Drop Down List Default Selected Value in MVC C#.

Controller:
DataTable dt = new DataTable();
            dt.Columns.Add("Value", typeof(int));
            dt.Columns.Add("Text", typeof(string));
            dt.Rows.Add(1, "Arul");
            dt.Rows.Add(2, "Kumar");
            dt.Rows.Add(3, "Arulkumar");
           

            ViewBag.DDL = new SelectList(dt.AsDataView(), "Value", "Text",2);
//where 2-for selected value Kumar
View
//DDL is viewbag name
@Html.DropDownList("DDL ", null, htmlAttributes: new { @class = "form-control" })

Monday, 18 July 2016

Place search using Google API

Live Example Here
<!--header-->
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>

<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
//var city = place.geometry.location.city();
//alert(address);
//for testing purpose alert
var mesg = "Address: " + address;
mesg += "\nLatitude: " + latitude;
mesg += "\nLongitude: " + longitude;
// alert(mesg);
//$("#address").val(address);
//$("#latitude").val(latitude);
//$("#longitude").val(longitude);
});
});
</script>
</head>

<body>
<textarea id="txtPlaces" name="txtPlaces" placeholder="Enter place to search" class="f-location" required></textarea>
</body>
</html> 

Monday, 11 July 2016

Image upload through ajax

// create model for controller
var model = new FormData();
model.append('Name', $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()));
model.append('Email', $.trim($contestForm.find('[name="email"]').val().toLowerCase()));
model.append('City', $.trim($contestForm.find('[name="cuidad"]').val()));
model.append('Title', $.trim($contestForm.find('[name="title"]').val()));
model.append('Description', $.trim($contestForm.find('[name="description"]').val()));
model.append('CountryCode', 'co');
model.append('Image', $contestForm.find('[name="file-es"]')[0].files[0]);  // this has the file for sure

$.ajax({
    url: '/Umbraco/api/ControllerName/CreateContestEntry',
    type: 'POST',
    dataType: 'json',
    data: model,
    processData: false,
    contentType: false,// not json
    complete: function (data) {
        var mediaId = $.parseJSON(data.responseText); //?

    },
    error: function (response) {
        console.log(response.responseText);
    }
});

Shortcut key sample in javascript

Shortcut key sample
$(window).keydown(function(e) {
  switch (e.keyCode) {
    case 37: // left arrow key
    case 38: // up arrow key
      e.preventDefault(); // avoid browser scrolling due to pressed key
      // TODO: go to previous image
      return;
    case 39: // right arrow key
    case 40: // up arrow key
      e.preventDefault();
      // TODO: go to next image
      return;
  }
});

Sunday, 3 July 2016

Data Columns to combined string Without Loop in C#


string prd_str = string.Join(", ", DataTableDt.Rows.OfType<DataRow>().Select(r => r[3].ToString()));

Join Two DataTables Using LINQ in C#

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into lj
             from r in lj.DefaultIfEmpty()
             select dtResult.LoadDataRow(new object[]
             {
                dataRows1.Field<string>("ID"),
                dataRows1.Field<string>("name"),
                r == null ? 0 : r.Field<int>("stock")
              }, false);