Tuesday, 17 December 2013

Auto Upgrade MVC 3 To MVC 4

Install-Package UpgradeMvc3ToMvc4

http://nugetmusthaves.com/Package/UpgradeMvc3ToMvc4
Hope this help you !



Wednesday, 11 December 2013

Showing loading animation in center of page while making a call to Action method in MVC



Now, use javascript to show it in and hide, when an ajax request starts. 
<script type="text/javascript">
    $(document).ajaxStart(function () {
        $('#spinner').show();
    }).ajaxStop(function () {
        $('#spinner').hide();
    });
</script>


Style the div element to position it on the centre of the browser.
<style>
div#spinner
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    text-align:center;
    margin-left: -50px;
    margin-top: -100px;
    z-index:2;
    overflow: auto;
}  
</style>


Put the html for the loader in the page.
<div id="spinner">
    <img src="~/Images/googleLarge.gif" alt="Loading..."/>
</div>

Hope this help you !



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;
 
 

Saturday, 26 October 2013

How to render a DateTime in a specific format in ASP.NET MVC 3?

If all you want to do is display the date with a specific format, just call:
@Model.LeadDate.ToString("dd-MMM-yyyy")

@Model.LeadDate.ToString("MM/dd/yy")
It will result in following format,

26-Sep-2013
10/26/13

Thursday, 24 October 2013

Email validation in mvc

[Required(ErrorMessage = "Email Address is required")]
[DisplayName("Email Address")]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
ErrorMessage = "Email is is not valid.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

Tuesday, 22 October 2013

validating email address using regular expression on razor page/mvc

Alternatively in razor @@ is a normal @ symbol, it is working fine..

/^[a-zA-Z0-9_.-]+@@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{0,4}$/

Thursday, 12 September 2013

custom paging using stored procedure sql server

/* create table */
create table tblCustomPaging (StudentName varchar(100),MobileNo varchar(20))

/* Insert into table */
insert into tblCustomPaging values('Amit','9876543210')
insert into tblCustomPaging values('Abhishek','8567575700')
insert into tblCustomPaging values('Sumit','7456456460')
insert into tblCustomPaging values('Bhuppy','9567575788')
insert into tblCustomPaging values('CP','8867575788')
insert into tblCustomPaging values('Sandeep','7767575788')
insert into tblCustomPaging values('OP','9967575788')
insert into tblCustomPaging values('Tarun','8867575700')
insert into tblCustomPaging values('Sachin','8867575700')
insert into tblCustomPaging values('Rajeev','9876543210')
insert into tblCustomPaging values('TK','9876541111')
insert into tblCustomPaging values('Mukesh','9876522222')

Method (1)

; With tmpResult As ( SELECT Row_Number() Over (ORDER BY StudentName) as RowNumber,
 StudentName, MobileNo from tblCustomPaging  as a )
 SELECT a.*, b.MaxRecords FROM tmpResult a CROSS JOIN
    (SELECT count(*) as MaxRecords FROM tmpResult) b
    WHERE RowNumber >  ((2 - 1) * 5)  and RowNumber <= (2 * 5) ORDER BY 1

Method (2)

/* create store procedure */

create proc USP_CustomPagin
@pageSize int=5,   
@pageNumber int=1 ,
@criteria varchar(max)='' 
as   
declare @endRowNumber int   
declare @startRowNumber int   
set @endRowNumber = @pageSize * @pageNumber   
set @startRowNumber  = (@endRowNumber - @pageSize)+ 1   
   
exec('select top '+ @pageSize +' Sno,totalCount, StudentName, MobileNo from (   
        select (select count(*) from tblCustomPaging where 0=0 '+  @criteria + ') as totalCount,   
        row_number() over(order by StudentName)Sno, StudentName, MobileNo   
        FROM tblCustomPaging  where 0=0 '+  @criteria + ' )as d   
            where d.sno between '+ @startRowNumber +' and  '+ @endRowNumber )


/* Run below query like */
USP_CustomPagin
USP_CustomPagin 5,1
USP_CustomPagin 5,2
USP_CustomPagin 5,1,' and StudentName Like ''%a%'' '
USP_CustomPagin 5,1,' and StudentName Like ''%a%'' OR MobileNo like ''%88%'''

Wednesday, 11 September 2013

How can we plug an ASP.NET MVC into an existing ASP.NET application ?

We can combine ASP.NET MVC into an existing ASP.NET application by following the below procedure:

First of all, you have to add a reference to the following three assemblies to your existing ASP.NET application:

i) System.Web.Routing
ii) System.Web.Abstractions
iii) System.Web.Mvc

The ASP.NET MVC folder should be created after adding these assembly references.
Add the folder Controllers, Views, and Views | Shared to your existing ASP.NET application.
And then you have to do the necessary changes in web.config file.
For this you can refer to the below link:

http://www.packtpub.com/article/mixing-aspnet-webforms-and-aspnet-mvc

Saturday, 7 September 2013

asp.net mvc 3 - Converting DateTime format using razor

Tricky solution : 
 @Html.TextBoxFor(m => m.fromData, new { @Value = Model.fromData.ToString("d") })

Tuesday, 30 July 2013

Restrict to numeric id only in mvc routing

Suppose we have defined the following route in our application and you want to restrict the incoming request url with numeric id only. Now let's see how to do it with the help of regular expression.
routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = 
 UrlParameter.Optional } //Default values for parameters
);

Restrict to numeric id only

routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = 
 UrlParameter.Optional },//Default values for parameters
 new { id = @"\d+" } //Restriction for id
);

Now for this route, routing engine will consider only those URLs which have only numeric id like as http://abc.com/Admin/Product/1 else it will considers that url is not matched with this route.

Monday, 3 June 2013

Get the url to the virtual root for the current request

Example(1)
Uri requestUri = Context.Request.Url;
string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);


Example(2)
This can be done much easier with the following code:
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Wednesday, 1 May 2013

http - How to check if a file exists on a server using VB.net

 Dim _Result As String
 Dim url
 url = dt.Rows(i)("ImageUrl").ToString()

 Dim myRequest As System.Net.HttpWebRequest = System.Net.WebRequest.Create(url)
 Dim myResponse As HttpWebResponse

   Try
    myResponse = myRequest.GetResponse()
 '_Result = myResponse.StatusCode.ToString();
    _Result = "1"
   Catch ex As System.Exception
    _Result = "0" 
   Finally
    myResponse.Close()
    myRequest = Nothing
    myResponse = Nothing
    GC.Collect()
   End Try
   Response.write(_Result)

Friday, 12 April 2013

How to use Google Maps with marker in ASP.NET, MVC

Copy-paste this code

<script type="text/javascript"  src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/src/markermanager.js"></script>


<h2>MAPS</h2>
<div id="map_canvas" style="height: 400px; width:100%;"></div>

<script language="javascript" type="text/javascript">
    var map;
    var mgr;

    function initialize() {
        var myOptions = {
            zoom: 14,
            center: new google.maps.LatLng(26.32849908419746, 73.11118125915527),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        mgr = new MarkerManager(map);
        var infoWindow = new google.maps.InfoWindow({ content: "SmartSign" });
        google.maps.event.addListener(mgr, 'loaded', function () {

        
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(26.32849908419746, 73.11118125915527),
                    html: "Om Prakash Bishnoi, House No : 83, Bheru Nagar, Banaar Road, Jodhpur, Rajasthan"
                });

                google.maps.event.addListener(marker, "click", function () {
                    infoWindow.setContent(this.html);
                    infoWindow.open(map, this);
                });
                mgr.addMarker(marker, 0);
            mgr.refresh();
        });
    }
    $(document).ready(function () {
        initialize();
    });
</script>

Friday, 29 March 2013

javascript maintain page scroll position

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
 <title>Test Page</title>
 <script type="text/javascript">
 function callTest(value)
 {
   alert(value);
 }
 </script>
</head>

<body>
 <form id="form1" runat="server">
  <table>
   <tr>
    <td style="height: 300px;">
     <a href="javascript:void(0);" id="A1" onclick="javascript:callTest('Add');" >Add</a>
     <p> Description 1............</p>
    </td>
   </tr>
   <tr>
    <td style="height: 300px;">
     <a href="javascript:void(0);" id="A2" onclick="javascript:callTest('Edit');" >Edit</a>
     <p> Description 2............</p>
    </td>
   </tr>
   <tr>
    <td style="height: 300px;">
     <a href="javascript:void(0);" id="A3" onclick="javascript:callTest('Delete');" >Delete</a>
     <p> Description 3............</p>
    </td>
   </tr>
   <tr>
    <td style="height: 300px;">
     <a href="javascript:void(0);" id="A4" onclick="javascript:callTest('View');" >View</a>
     <p> Description 4............</p>
    </td>
   </tr>
  </table>
 </form>
</body>
</html>

Get Page Name In Javascript ??

  <script type="text/javascript">

        var sPath = window.location.pathname;
       var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
       alert(sPage);

</script>

Thursday, 28 March 2013

Get Cookie Value From Javascript ??

function getCookie(cookiename)
  {
  // Get name followed by anything except a semicolon
  var cookiestring=RegExp(""+cookiename+"[^;]+").exec(document.cookie);
  // Return everything after the equal sign
  return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+/,"").replace("=","") : "");
  }

var myCookie = getCook('cookieName');

Saturday, 9 March 2013

how to add subTotal, grandTotal in sql query

DECLARE @t TABLE (RowNum INT IDENTITY(1,1),Grp CHAR(1), Val INT)

 INSERT INTO @t
 SELECT NULL, 1 UNION ALL
 SELECT 'A', 2 UNION ALL
 SELECT 'A', 3 UNION ALL
 SELECT 'A', 3 UNION ALL
 SELECT 'B', 4 UNION ALL
 SELECT 'A', 3 UNION ALL
 SELECT 'B', 5

 SELECT d.Grp,d.GroupTotal
   FROM (
         SELECT RowNum,
                Grp = CASE
                        WHEN GROUPING(Grp) = 0 AND GROUPING(Val) = 0 THEN Grp
                        WHEN GROUPING(Grp) = 0 AND GROUPING(Val) = 1 THEN 'Sub Total ' + ISNULL(grp,'NULL')
                        ELSE 'Grand Total'
                      END,
                GroupTotal = SUM(Val)
           FROM @t
          GROUP BY Grp,Val,RowNum WITH ROLLUP
        ) d
  WHERE RowNum > 0 OR Grp LIKE '%Total%'


Grp                  GroupTotal
NULL                   1            
Sub Total N         1            
A                          2            
A                          3            
A                          3            
A                          3            
Sub Total A         11          
B                          4            
B                          5            
Sub Total B         9            
Grand Total        21           

Friday, 1 March 2013

Write the code for selecting the 1st div, 3rd div, 3rd Last div, last div, and for even and odd div elemets ?

<div class="questions">
    <div class="myDiv"> Question</div>
    <div class="
myDiv"> Question</div>
    <div class="
myDiv"> Question</div>
    <div class="
myDiv"> Question</div>
    <div class="
myDiv"> Question</div>
    <div class="
myDiv"> Question</div>
</div>


first div : $("div.questions > div:first").css("color", "red");
3rd div : $("div.questions > div:nth-child(3)").css("color", "red");

3rd last div : $("div.questions > div::nth-last-child(3)").css 
                    ("color", "red"); 
last div : $("div.questions > div:last").css("color", "red");
even div : $("div.questions > div:even").css("color", "red");
odd div  : $("div.questions > div:odd").css("color", "red");


Thursday, 28 February 2013

Route data inside a controller

We can access routing data inside a controller using the RouteData object.

public ActionResult Index()
{
   ViewBag.Message = String.Format("{0}---{1}---{2}",
                                    RouteData.Values["controller"],        
                                    RouteData.Values["action"],
                                    RouteData.Values["id"]);
    Return View();
}

Wednesday, 16 January 2013

Removing the WebForms View Engine in MVC

If Razor is the only view engine you use in an ASP.NET MVC application, then it makes sense to remove the Web Forms view engine and save some cycles. Otherwise, the MVC runtime will go looking for .aspx and .ascx files when it tries to locate a view or template. A small savings, but just 2 lines of code required during application startup.

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());