Monday, 30 July 2018

ActionVerbs in MVC

The ActionVerbs selector is used when you want to control the selection of an action method based on a Http request method. For example, you can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request.

MVC framework supports different ActionVerbs, such as HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions & HttpPatch. You can apply these attributes to action method to indicate the kind of Http request the action method supports. If you do not apply any attribute then it considers it a GET request by default.

The following figure illustrates the HttpGET and HttpPOST action verbs.
The following table lists the usage of http methods:

Http method Usage
GET To retrieve the information from the server. Parameters will be appended in the query string.
POST To create a new resource.
PUT To update an existing resource.
HEAD Identical to GET except that server do not return message body.
OPTIONS OPTIONS method represents a request for information about the communication options supported by web server.
DELETE To delete an existing resource.
PATCH To full or partial update the resource.

The following example shows different action methods supports different ActionVerbs:

Example: ActionVerbs
public class StudentController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult PostAction()
    {
        return View("Index");
    }


    [HttpPut]
    public ActionResult PutAction()
    {
        return View("Index");
    }

    [HttpDelete]
    public ActionResult DeleteAction()
    {
        return View("Index");
    }

    [HttpHead]
    public ActionResult HeadAction()
    {
        return View("Index");
    }
       
    [HttpOptions]
    public ActionResult OptionsAction()
    {
        return View("Index");
    }
       
    [HttpPatch]
    public ActionResult PatchAction()
    {
        return View("Index");
    }
}
You can also apply multiple http verbs using AcceptVerbs attribute.
GetAndPostAction method supports both, GET and POST ActionVerbs in the following example:

Example: AcceptVerbs
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
    return RedirectToAction("Index");
}
  Points to Remember :
ActionVerbs are another Action Selectors which selects an action method based on request methods e.g POST, GET, PUT etc.
Multiple action methods can have same name with different action verbs. Method overloading rules are applicable.
Multiple action verbs can be applied to a single action method using AcceptVerbs attribute.

QS


ASP.Net Page Method using jQuery AJAX Example
function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetCurrentTime",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}



How to select second div using jQuery in a webpage?

If a webpage has 2 div tags like
<div>hello</div>
<div>hello</div>

$("div:eq(1)");


How do I get the value of a selected item of a radio button list 
with jquery
$('#btnTest').click(function()
    {
        alert($('#<%=RadioButtonList1.ClientID %> input[type=radio]:checked').val());
    });
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
            <asp:ListItem Text="No" Value="2"></asp:ListItem>
 </asp:RadioButtonList>
<input type="button" id="btnTest" value="Uncheck" /> 


Difference between document.getElementById and document.getElementsByClassName

document.getElementById  returns a single DOM element whose ID matches your query.
 document.getElementsByClassName  returns an HtmlCollection - an array-like structure containing the DOM elements that matched your query

<div class="move">add padding</div>
<div class="move">add padding</div>
<button type="button" onclick="movefun()">Set left padding</button>
<script>
    function movefun() {
        var elements = document.getElementsByClassName("move");
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.paddingLeft = "50px";
        }
    }
</script>

OUTPUT:add padding
                add padding

Display Data In Table Format In MVC

Add Employee Class in Model folder.
  1. class Employee  
  2. {  
  3.   
  4.     public int EmployeeId { getset; }  
  5.   
  6.     public string FirstName { getset; }  
  7.   
  8.     public string LastName { getset; }  
  9.   
  10.     public string Email { getset; }  
  11.   
  12.     public int Salary { getset; }  
  13.   
  14.     public string Company { getset; }  
  15.   
  16.     public string Dept { getset; }  
  17.   
  18. }  
Home Controller Code
  1. public class HomeController : Controller  
  2. {  
  3.     private List<Employee> emp;  
  4.     public HomeController()  
  5.     {  
  6.         emp = new List<Employee>()  
  7.         {  
  8.             new Employee()  
  9.             { EmployeeId =1,FirstName="Rakesh",LastName="Kalluri", Email="raki.kalluri@gmail.com", Salary=30000, Company="Summit", Dept="IT" },  
  10.             new Employee()  
  11.             { EmployeeId =2,FirstName="Naresh",LastName="C", Email="Naresh.C@gmail.com", Salary=50000, Company="IBM", Dept="IT" },  
  12.             new Employee()  
  13.             { EmployeeId =3,FirstName="Madhu",LastName="K", Email="Madhu.K@gmail.com", Salary=20000, Company="HCl", Dept="IT" },  
  14.             new Employee()  
  15.             { EmployeeId =4,FirstName="Ali",LastName="MD", Email="Ali.MD@gmail.com", Salary=26700, Company="Tech Mahindra", Dept="BPO" },  
  16.             new Employee()  
  17.             { EmployeeId =5,FirstName="Chithu",LastName="Raju", Email="Chithu.Raju@gmail.com", Salary=25000, Company="Dell", Dept="BPO" },  
  18.             new Employee()  
  19.             { EmployeeId =6,FirstName="Nani",LastName="Kumar", Email="Nani.Kumar@gmail.com", Salary=24500, Company="Infosys", Dept="BPO" },  
  20.   
  21.         };  
  22.     }  
  23.     public ActionResult Index()  
  24.     {  
  25.   
  26.         return View(emp);  
  27.     }  
Table Format Data Displaying in ForEach
Index.Cshtml
  1. @model IEnumerable<List_Data_Binding_in_MVC.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6. <div><b>Table Format Data Displaying in ForEach</b><br /></div>  
  7. <table class="table table-bordered table-responsive table-hover">  
  8.     <tr>  
  9.         <th>Employee Id </th>  
  10.         <th>First Name </th>  
  11.         <th>Last Name </th>  
  12.         <th>Email</th>  
  13.         <th>Salary</th>  
  14.         <th>Company</th>  
  15.         <th>Department</th>  
  16.     </tr>  
  17.     @foreach (var d in Model)  
  18.     {  
  19.         <tr>  
  20.             <td>@d.EmployeeId</td>  
  21.             <td>@d.FirstName</td>  
  22.             <td>@d.LastName</td>  
  23.             <td>@d.Email</td>  
  24.             <td>@d.Salary</td>  
  25.             <td>@d.Company</td>  
  26.             <td>@d.Dept</td>  
  27.   
  28.         </tr>  
  29.     }  
  30. </table>  
Output

run


Friday, 27 July 2018

Singleton Design Pattern

What is Singleton Design Pattern?
  1. Ensures a class has only one instance and provides a global point of access to it.
  2. A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance.
  3. Most commonly, singletons don't allow any parameters to be specified when creating the instance, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)
  • A single constructor, that is private and parameterless.
  • The class is sealed.
  • A static variable that holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Advantages
The advantages of a Singleton Pattern are:
  1. It can be also inherit from other classes.
  2. It can be lazy loaded.
  3. It has Static Initialization.
  4. It provides a single point of access to a particular instance, so it is easy to maintain.
Disadvantages
The disadvantages of a Singleton Pattern are:
  1. Unit testing is more difficult (because it introduces a global state into an application).

Thread Safety Singleton
  • This implementation is thread-safe.
  • In the following code, the thread is locked on a shared object and checks whether an instance has been created or not.
  • This takes care of the memory barrier issue and ensures that only one thread will create an instance.
  • For example: Since only one thread can be in that part of the code at a time, by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false.
  • The biggest problem with this is performance; performance suffers since a lock is required every time an instance is requested.
public sealed class Singleton
{
    Singleton()
    {
    }

    private static readonly object padlock = new object();

    private static Singleton instance = null;
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Singleton class vs. Static methods
The following conpares Singleton class vs. Static methods:
  1. A Static Class cannot be extended whereas a singleton class can be extended.
  2. A Static Class can still have instances (unwanted instances) whereas a singleton class prevents it.
  3. A Static Class cannot be initialized with a STATE (parameter), whereas a singleton class can be.
  4. A Static class is loaded automatically by the CLR when the program or namespace containing the class is loaded.