Saturday, 30 November 2013

MVC 3 AJAX redirecting instead of updating DIV

Finally I tracked it down to two issues.
I realized that if I set UnobtrusiveJavaScriptEnabled to false in my web.config file, everything worked.


A second issue, and one that I suspect others may run into as well, is that I didn’t have a reference to jquery.unobtrusive-ajax.min.js in my master (or child) page.  Since MVC 3 uses UnobtrusiveJavaScript by default, it’s essential that the Javascript files are referenced, otherwise it can break unrelated Javascript, making it obtrusive rather than unobtrusive.  Obviously not the desired effect.
The correct scripts that are required for MVC+AJAX plus UnobtrusiveJavaScript are:

  1. <script src="@Url.Content("~/Scripts/jquery-1.4.1.min.js")" type="text/javascript"></script>
  2. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  3. <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
  4. <script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
  5. <script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>

Hope this help you.

Wednesday, 27 November 2013

Composable LINQ to SQL query with dynamic Parameters

var _companyId = 1;
var Name = "OP";
var FromDate;
var  EmpId;
 var query = from audit in edmx.tblAudit
              from asst in edmx.tblAssets.Where(x => x.AutoId == audit.Asset_Id)
              where audit.Company_Id == _companyId
                  && asst.Name.Contains(string.IsNullOrEmpty(Name) ? asst.Name : Name)
           select new
             {
                        AssetName = asst.Name,
                        Serial_No = asst.Serial_No,
                        EmployeeName = audit.EmpName,
                        Date = audit.Audit_Date
             };

if (FromDate.Length > 7)
{
     var _FromDate = Convert.ToDateTime(FromDate);
     query = query.Where(x => x.Date >= _FromDate);
}
if (EmpId.Length > 0)
{
     var _empId = Convert.ToInt16(EmpId);
     query = query.Where(x => x.EmployeeId == _empId);
 }

 var auditData = (from asst in query
          asst.AssetName, asst.Serial_No, asst.EmployeeName,
          asst.Date, asst.AssetType
          }).OrderBy(x => x.AssetType).ToList();



looking like :
SELECT AssetName, Serial_No, EmployeeName,Date,AssetType FROM [dbo].[tblAssets] AS [t0]
 Inner join tblAudit t1 on t1.Asset_Id = t0.AutoId
WHERE (t0.
AssetName like '%op%') AND (t0.Fromdata >= '01/01/2013') AND (t1.empId = 11) 

for more information please see below link :
http://blogs.msdn.com/b/swiss_dpe_team/archive/2008/06/05/composable-linq-to-sql-query-with-dynamic-orderby.aspx?CommentPosted=true#commentmessage

Tuesday, 19 November 2013

Remove character from string using javascript


var test = '1,3,4,5,6';??

//to remove number/chracter
function removeNum(string, val){
   var arr = string.split(',');
   for(var i in arr){
      if(arr[i] == val){
         arr.splice(i, 1);
         i--;
      }
  }           
 return arr.join(',');
}

var str = removeNum(test,3);   
document.write(str); // output 1,4,5,6

Shortest method to convert an array to a string in c#/LINQ


int[] intarray = { 1, 2, 3, 4, 5 };
string getString = String.Join(",", arr.Select(p=>p.ToString()).ToArray())

Convert Int array to string array
string[] result = intarray.Select(x=>x.ToString()).ToArray();

Monday, 18 November 2013

MVC Force Validation of Hidden Fields

I need to enable the validation of hidden fields using ASP.net MVC3/4 unobtrusive validation.
The reason behind this is a jquery plugin which hides the original input field to show something fancier.
But this disables validation of the field as it becomes hidden.

Finally i found perfect solution.
Now we are able to validate hidden field with following code.

$( document ).ready(function()
{
   var validator = $("#myFormId").data('validator');
   validator.settings.ignore = "";
});

Hope this help you.

how to write 'where in' style queries using linq to entities

string SerialNoCollection ="SR-1,SR-2,SR-3,SR-4,SR-5,SR-6";
 var serialNo = SerialNoCollection.Split(',').Select(x => x);

var myFilterData =  from asset in tblAssets where
                        (!serialNo.Any() || serialNo.Contains(asset.Serial_No))
                        select asset ;       

Sunday, 17 November 2013

how to show div in center of screen using jquery

Html

<div class="loading" id="pageLoading" name="pageLoading" style="display: none;">
                <img src="/Images/loading.gif" alt="Loading....." />
 </div>

css

<style type="text/css">
.loading{
    z-index:10001;
}
.loading div{
    margin: auto 0px;
    text-align:center;
    vertical-align:middle;
}
</style>

script

<script type="text/javascript" language="javascript">
   function pageLoading()
   {
        var $loading = $(".loading");
        var windowH = $(window).height();
        var windowW = $(window).width();

        $loading.css({
            position: "fixed",
            left: ((windowW - $loading.outerWidth()) / 2 + $(document).scrollLeft()),
            top: ((windowH - $loading.outerHeight()) / 2 + $(document).scrollTop())
        })
        $("#pageLoading").toggle();
    }
</script>

Saturday, 16 November 2013

Google Maps Not Working in jQuery Tabs !! problem solved

Try to load a map when user clicks on tab which contains your gMap
div.

        function clientActiveTabChanged(sender, args) {
            if(sender.get_activeTabIndex() == 1) {
                loadGMap();  // call google map load/initialize function
            }

Brillant that works !!!


Google maps draggable marker , latitude longitude from address

copy paste below code and run the application -  :)

<html>
<head>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">
        var geocoder;
        var map;
        var markersArray = [];
        var marker;
        var infowindow = new google.maps.InfoWindow();

        function initialize() {
            geocoder = new google.maps.Geocoder();
            var myOptions = {
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            codeAddress();

            google.maps.event.addListener(map, 'click', function (event) {
                placeMarker(event.latLng);
            });

            google.maps.event.addListener(marker, 'drag', function (event) {
                document.getElementById("divLatitude").innerHTML = event.latLng.lat();
                document.getElementById("divLongitude").innerHTML = event.latLng.lng();
                placeMarkerOP(event.latLng);
            });

            google.maps.event.addListener(marker, 'dragend', function (event) {
                document.getElementById("divLatitude").innerHTML = event.latLng.lat();
                document.getElementById("divLongitude").innerHTML = event.latLng.lng();
                placeMarkerOP(event.latLng);
            });
        }

        function codeAddress() {
            var address = document.getElementById("address").value;
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    clearOverlays();

                    document.getElementById("address").value = results[0]['formatted_address'];
                    document.getElementById("divLatitude").innerHTML = results[0].geometry.location.ob;
                    document.getElementById("divLongitude").innerHTML = results[0].geometry.location.pb;
                  
                    map.setCenter(results[0].geometry.location);
                    marker = new google.maps.Marker({
                        map: map,
                        title: results[0]['formatted_address'],
                        position: results[0].geometry.location,
                        animation: google.maps.Animation.DROP
                    });

                    infowindow.setContent(results[1].formatted_address);
                    infowindow.open(map, marker);

                    markersArray.push(marker);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }

        function placeMarker(location) {

            geocoder.geocode({ 'latLng': location }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        clearOverlays();

                        document.getElementById("address").value = results[1].formatted_address;
                        document.getElementById("divLatitude").innerHTML = results[0].geometry.location.ob;
                        document.getElementById("divLongitude").innerHTML = results[0].geometry.location.pb;

                        marker = new google.maps.Marker({
                            position: location,
                            title: results[1].formatted_address,
                            map: map,
                            draggable: true,
                            animation: google.maps.Animation.DROP
                        });
                        infowindow.setContent(results[1].formatted_address);
                        infowindow.open(map, marker);

                        markersArray.push(marker);

                        google.maps.event.addListener(marker, 'click', toggleBounce);

                        google.maps.event.addListener(marker, 'drag', function (event) {
                            document.getElementById("divLatitude").innerHTML = event.latLng.lat();
                            document.getElementById("divLongitude").innerHTML = event.latLng.lng();

                            placeMarkerOP(event.latLng);
                        });

                        google.maps.event.addListener(marker, 'dragend', function (event) {
                            document.getElementById("divLatitude").innerHTML = event.latLng.lat();
                            document.getElementById("divLongitude").innerHTML = event.latLng.lng();

                            placeMarkerOP(event.latLng);
                        });

                        map.setCenter(location);

                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });
        }


        function placeMarkerOP(location) {
            geocoder.geocode({ 'latLng': location }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        document.getElementById("address").value = results[1].formatted_address;
                        infowindow.setContent(results[1].formatted_address);
                    }
                }
            });
        }



        function clearOverlays() {
            if (markersArray) {
                for (i in markersArray) {
                    markersArray[i].setMap(null);
                }
            }
        }

        function toggleBounce() {

            if (marker.getAnimation() != null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        }
       
    </script>
</head>

<body onload="initialize()" >
    <table width="800px" cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td align="center">
                <h3>Latitude : <div id="divLatitude" name="divLatitude"></div> </h3>
                <h3>Longitute : <div id="divLongitude" name="divLongitude"></div></h3>
                <p><textarea id="address" rows="2" >Paota, Jodhpur,Rajasthan, India</textarea><input type="button" value="Show" onclick="codeAddress()"></p>
            </td>
        </tr>
        <tr>
            <td>
                <div id="map_canvas" style="height:500px; width:100%;" >
                </div>
            </td>
        </tr>
    </table>
</body>

</html>


Hope this help you !


Thursday, 14 November 2013

Linq to sql: Order by desc, then order by asc?

var query = from person in people
            orderby person.Name descending, person.Age descending
            select person.Name;

is equivalent to:

var query = people.OrderByDescending(person => person.Name)
                  .ThenBy(person => person.Age)
                  .Select(person => person.Name);


Hope this help you !

Wednesday, 13 November 2013

ASP.NET MVC ajax.beginform : No parameterless constructor defined for this object

This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:

public class MyViewModel
{
    public SelectList employeeList {get;set;}
}
 
 You'll need to refactor your model to do it a different way if this is the cause. So using an
IEnumerable<SelectListItem> and writing an extension method that
creates the drop down list with the different property definitions:

public class MyViewModel
{
    public IEnumerable<SelectListItem> employeeList { get; set; }
}


Perfect solution !

Saturday, 9 November 2013

Unobtrusive / client side validation doesn't work with Ajax.BeginForm

You need to add those 2 files in your Partial View even if it is already in the Shared/_Layout.cshtml:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

Or place this in your Partial:

<script type="text/javascript" language=javascript>
    $.validator.unobtrusive.parse(document);
</script>


Perfect solution.



Wednesday, 6 November 2013

LEFT JOIN in LINQ to Entities?

DefaultIfEmpty is used for left joins for EntityFramework 4+

var query = from u in context.Users
    from a in context.Addresses
          .Where(x => u.Primary2Address == x.AddressiD)
          .DefaultIfEmpty()
    from s in context.States
          .Where(x => a.Address2State == x.StateID)
          .DefaultIfEmpty()
    from c in context.Countries
          .Where(x => a.CountryID == x.CountryID)
          .DefaultIfEmpty()
select u.UserName;