How to capture Multiple Button events in MVC

1. Suppose I have one View say Operations.
2. Where I have got multiple buttons which performs different operations (add, edit, delete or may be update)
3. So how will I be able to capture these events while I am having only one View and only one Action method ?
4. Lets consider following Example.

Operations.aspx
<input type="submit" id="btnShowOriginal" value="Show Original" name="Submit" title="Click to Show Original"  />
<input type="submit" id="btnShowConflict" value="Show Conflict" name="Submit" title="Click to Show Conflict" />
<input type="hidden" id="hdnConflictSchedID" name="hdnConflictSchedID" value="" />
<input type="hidden" id="hdnSchedID" value="0" name="hdnSchedID" />

When we add a Controller for this View, so we will get an ActionResult method just as below.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddEditSchedule(string Submit) { }

In above Signature of method we have passed one string Parameter “Submit” which will refer to the submit button we have placed in View “Operations” above.
So now we can customized this method as follows :

public ActionResult AddEditSchedule(string Submit) { 
switch (Submit)
    {
	case "Save":
	    //your custom code will go here
	case "Cancel":
	    //your custom code will go here
	case "Delete":
	    //your custom code will go here
	case "Show Conflict":
	    //your custom code will go here
	case "Show Original":
	    //your custom code will go here
	case "ThemeGreen":
	    //your custom code will go here
	case "ThemeBlue":
	    //your custom code will go here
	default:
	    //your custom code will go here
    }
}

.Net Interview Questions

  • CLR
  • CTS
  • Managed Code
  • Multi Threading
  • MVC
  • WPF vs Windows form
  • abstract class vs Interface
  • Delegates with types
  • Constructor
  • Anamous method
  • Method Extension
  • New features of 3.0 or 3.5 appart from controls and JS Intelligence (wants to know liNQ)
  • Web Services
  • WebServices vs WCF
  • Response.redirect vs Server.transwer
  • Indexes (Clustered and NonClustered)
  • Can Interface have Access Modifiers
  • Access Modifiers
  • WCF
  • String vs String Builder
  • Web.config (all parts)
  • Global.asax (what is use)
  • Remoting vs WebServices (When to use which one)
  • What Authentications you used in your project
  • Authentication types.
  • Types of Validators

Some more Questions:

  • Can we overload methods in WCF Service or Web Service?
    Yes for a WCF Service use the Name property of OperationContractAttribute class
    example:
    [ServiceContract]
    interface ddd
    {
    [OperationContract(Name = “one”)]
    int calc(int a,int b);
    [OperationContract(Name = “two”)]
    double calc(double a,double b);
    }

    1)For a Web Service use the MessageName property of WebMethodAttribute class

    2)
    [WebMethod]
    public string HelloWorld(string a) {
    return “Hello”+” “+a;
    }
    [WebMethod(MessageName=”second”)]
    public string HelloWorld()
    {
    return “Hello second”;
    }

  • What is Window service
  • Diffrence b/w window service & .exe
  • what is entery point of window sercvice
  • Diff b/w Abstract Class & Interface
  • What is LINQ, which namespace is use for LINQ
  • what is purpose of isPOstback
  • What is DataContract
  • What is Interface with example
  • What are diffrent methods used for data retrival in ADO.net
  • INdexes in detail (cluster & non cluster)
  • why triggers are used
  • how WCF architecture works
  • diffrence b/w web service & WCF
  • is there anyway by which I can use ASP.net application variable like session in webservice & how
  • what are design Patterns
  • What is Ajax & full form of AJAX
  • How Ajax works
  • What is Asynchronous & synchronous Call
  • how can u detect Browser in Javascript (navigator.appCodeName)
  • how can you validate that a number in Javascript (isNan)
  • What is the basic diffrence in style=Disaply:none & Visibility=”Hidden”
  • What is Design Patterns?
  • What is Delegate?
  • What is Event
  • What is return type of Event
  • If I decalerd a Event with Private access modifier what will happen
  • what are application variables
  • what is diffrence between cookie var & cache variable
  • What is use of ClientScript.RegisterClientScriptBlock
  • What are main features included in .net 3.5 framework.
  • how can you redirect a user to diffrent page through Javascript
  • what is diffence b/w string & string builder
  • Is ajax work if Javascript is disable on browser level
  • what is WSDL?
  • what is DTD (this quest is in context of XML)

Some more Questions:

  • What is WCF Throttling
  • Execution process of .net Console Application
  • Can we use multiple protocols in WCF Service.

I have found some good sites for Interview Questions :-

http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=58
http://www.dotnetuncle.com

LINQ Operations

.NET Language-Integrated Query (LINQ) defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable-based information source.

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="JSON.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        LINQ Demo :-
    </h2>
       <table style="width:100%;">
        <tr>
            <td>
                <asp:Button ID="btngetdata" runat="server" onclick="btngetdata_Click" 
                    Text="Fill with LINQ" />
            </td>
            <td>
                <asp:DropDownList ID="ddlgetdata" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                    Text="Declaritive Short Hand " />
            </td>
            <td>
                <asp:DropDownList ID="ddlshorthand" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" 
                    Text="Lambda Expressions and Expression Trees" />
            </td>
            <td>
                <asp:DropDownList ID="ddlextressiontree" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button4" runat="server" onclick="Button4_Click" 
                    Text="LINQ anonymous methods" />
            </td>
            <td>
                <asp:DropDownList ID="ddlanonymous" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnwhere" runat="server" onclick="btnwhere_Click" 
                    Text="where" />
            </td>
            <td>
                <asp:DropDownList ID="ddlwhere" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btndatatable" runat="server" onclick="btndatatable_Click" 
                    Text="LINQ with DataTable" />
            </td>
            <td>
                <asp:DropDownList ID="ddlDatatable" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

Here we are having an Array on which we are going to Implement LINQ :

string[] names = { "Abhishek", "Rohit", "Mayank", 
                       "Rider", "Lucky", "Utkarsh", 
                       "Lakhan", "Manish" };

Below is the Source code how to fill a Dropdown list using Simple LINQ :-

protected void btngetdata_Click(object sender, EventArgs e)
{
    IEnumerable<string> data = from d in names
			       where d.Length < 6
			       select d.ToUpper();
    foreach (string da in data)
    {
	ddlgetdata.Items.Add(da.ToString());
    }
}

This above query can also be written as below, this approach is called Method based :-

protected void methodbased_Click(object sender, EventArgs e)
{
    IEnumerable<string> str = names
       .Where(s => s.Length < 6)
       .OrderBy(s => s)
       .Select(s => s.ToUpper());

    foreach (string da1 in str)
    {
	ddlshorthand.Items.Add(da1.ToString());
    }
}

Lambda Expressions and Expression Trees (Func delegate type) :-

protected void Button3_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = s => s.Length < 6;
    Func<string, string> Order = s => s;
    Func<string, string> sel = s => s.ToUpper();

    IEnumerable<string> d = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string i in d)
    {
	ddlextressiontree.Items.Add(i);
    }
}

We can also write the above method using anonymous methods (Delegates) like below :-

protected void Button4_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = delegate(string s)
    {
	return s.Length < 6;
    };

    Func<string, string> Order = delegate(string s)
    {
	return s;
    };

    Func<string, string> sel = delegate(string s)
    {
	return s.ToUpper();
    };

    IEnumerable<string> query = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string s in query)
    {
	ddlanonymous.Items.Add(s);
    }
}
protected void btnwhere_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    IEnumerable<string> query = names.Where(s => s[0] == 'A');
    foreach (string z in query)
    {
	ddlwhere.Items.Add(z);
    }
}

Now we are going to see how to implement LINQ on DataTable, However DataTable is not an IEnumerable type and LINQ is only work with IEnumerable Types.
So here we need to convert this DataTable to IEnumerable Types and then we can apply LINQ over it.

We can have a DataTable as follows :-

static DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Id", typeof(int));
    table.Columns.Add("Address", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    table.Rows.Add(1, "Indore", "Abhishek", DateTime.Now);
    table.Rows.Add(2, "Pune", "Rohit", DateTime.Now);
    table.Rows.Add(3, "Hydrabad", "Mayank", DateTime.Now);
    table.Rows.Add(4, "Mumbai", "Rider", DateTime.Now);
    table.Rows.Add(5, "Bangalore", "Lucky", DateTime.Now);
    return table;
}

In below code we have used “AsEnumerable()” method to make DataTable of IEnumerable Type.

protected void btndatatable_Click(object sender, EventArgs e)
{
    //AsEnumerable() Used here to convert Datatable (DataTable is NOT IEnumerable Type) in to IEnumerable type so that we can apply LINQ in it.
    var query = from data in GetTable().AsEnumerable()
		where data.Field<int>("Id") > 2 && data.Field<string>("Name").StartsWith("M")
		select new
		{
		    Name = data.Field<string>("Name"),
		    Id = data.Field<int>("Id")
		};

    foreach (var v in query)
    {
	ddlDatatable.DataTextField = v.Name.ToString();
	ddlDatatable.DataValueField = v.Id.ToString();
	ddlDatatable.Items.Add(v.Name.ToString());
    }
}

LINQ Demo

Note :-
As per my thinking this LINQ can be very usefull for small data to Operate on.. If we retrieve data from DB in bulk and keep it in memory so that we can apply LINQ on that data that is not a good option..

Html Extension method to generate Html Table.

We are creating a custom Html method Extension in which we write code to generate a class which will return you a html table.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Text;
using System.Reflection;

namespace LINQtoSQL.HtmlTable
{
     public static class HtmlTable
     {
        public static string DPHtmlTable(this HtmlHelper html, IEnumerable dataSource, string cssClassName, string noDataMessage, string columnLink)
        {
StringBuilder tableBuilder = new StringBuilder();
        tableBuilder.Append("<table cellspacing='0' cellpading='0' border='0' width='100%'>");
        IEnumerator tableEnumerator = dataSource.GetEnumerator();
        Type itemType;

        if (tableEnumerator.MoveNext() == false)
        {
               tableBuilder.AppendLine("<tr>");
               tableBuilder.AppendLine("<th>" + noDataMessage + "</th>");
               tableBuilder.AppendLine("</tr>");
               tableBuilder.AppendLine("</table>");
               return tableBuilder.ToString();
        }
        else
        {
               itemType = tableEnumerator.Current.GetType();
        }
               PropertyInfo[] properties = itemType.GetProperties();

 //Table Header column
               tableBuilder.AppendLine("<tr>");
               foreach (PropertyInfo property in properties)
               {
                 tableBuilder.AppendLine("<th>");
                 tableBuilder.Append(property.Name.ToString());
                 tableBuilder.AppendLine("</th>");
               }
                 tableBuilder.AppendLine("</tr>");

 //Table Data column
         foreach (object item in dataSource)
         {
            tableBuilder.AppendLine("<tr>");
            foreach (PropertyInfo property in properties)
            {
                 tableBuilder.Append("<td>");
                 if (property.Name.ToString().ToLower() == columnLink.ToString().ToLower()) {
                 tableBuilder.Append("<a onclick=alert("+ property.GetValue(item,null) +")>" + property.GetValue(item, null) + "</a>");
                }
                else
                {
                   tableBuilder.Append(property.GetValue(item, null));
                }
                  tableBuilder.Append("</td>");
            }
           tableBuilder.AppendLine("</tr>");
        }

        tableBuilder.Append("</table>");
         return tableBuilder.ToString();
    }
  }
}


You need to include the class we have created :-

<%@ Import Namespace="LINQtoSQL.HtmlTable" %>

This MVC table control can be used in your code as follows :-

<%=Html.DPHtmlTable((IEnumerable)this.ViewData.Model, "tableClass","No Data Available to Display!", "prodKey")%>

 

LINQ to SQL DataModel

Here In this very new topic we are going to learn how to display the Data from DataBase using LINQ to SQL..
This we will do using the DataContext class :
1.    For this we will need one DataBase and having any table as of your own Interest.. In my case I am using a very simple Table called “tblSoftware” which consists of three very simple fields namely id, Name and ProdKey.
2.    Now we will Include this DataBase in our application for that you need to follow these simple steps:
3.    Right click on “App_Data”  folder in your application and Click on “Add new Item”, there you select “SQL Server Database”
4.    Name that Database as “SoftwareDB”.
5.    When you will doubleClick this DataBase , then in Server Explorer you will get it along with all the tables Included in this DataBase.

7.    Just drag the table in blank space.
8.    Now we are going to display the name of Softwares on to the Page (HomeController >> Index)
9.    We have to put this below code In HomeController Class.

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LINQtoSQL;
using LINQtoSQL.Models;

namespace LINQtoSQL.Controllers
{
 [HandleError]
 public class HomeController : Controller
 {
 public ActionResult Index()
 {
 var dataContext = new SoftwareDataContext();
 var softwareData = from m in dataContext.Softwares
 select m;
 return View(softwareData);
 }

 public ActionResult About()
 {
 return View();
 }
 }
}

Now this above code will return a “softwareData” view and we can display this data in View Index.aspx.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace ="LINQtoSQL.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <p>
  <ul>
     <%  foreach (Software s in (IEnumerable)ViewData.Model) %>
    <% { %>
     <li>
        <%= s.Name %>
     </li>
    <% } %>
 </ul>
 </p>
</asp:Content>

 

Extending ASP.NET MVC HtmlHelper Class

Extending HtmlHelper Class in ASP.Net 2010

HtmlHelper Class can be used in ASP.Net MVC Framework to render HTML like textbox, Label, checkbox etc.

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

Now suppose if I want to render an Label using HtmlHelper Class, so that I can do as follows:

<%=Html.Label(“lblHome”) %>

Since these Html Helpers are build as an extension methods. This Extension methods can be made in two ways (according to me 🙂 )
1.    Easy Method of Extending HtmlHelper.
2.    Less Easy Method..
First we will go for the Easy Method  :
For  this we will make one folder in our MVC Application. We will add one Class and named it as “LabelHelper.cs” as shown in below screen shot.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PresentationDEMO.LabelHelper
{
 public class LabelHelper
 {
 public static string DPLabel(string target, string text)
 {
 return string.Format("<Label for='{0}'>{1}</label>", target, text);
 }
 public static string DPTextbox(string target, string text)
 {
 return string.Format("<input id='{0}' type='text' value='{1}'></input>", target, text);
 }
 }
}

And that’s it all Done.
Now Code below shows how to use this extension in View.
For this you need to Include Namespace/Class:

<%@ Import Namespace="PresentationDEMO.LabelHelper" %>
<%@ Import Namespace="PresentationDEMO.LabelHelperExtension" %>
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="PresentationDEMO.LabelHelper" %>
<%@ Import Namespace="PresentationDEMO.LabelHelperExtension" %>
<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
 About Us
</asp:Content>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
 <h2>About</h2>
 <p>
 <%= LabelHelper.DPLabel("lblFirstName","This is custom Label") %>
 <%= LabelHelper.DPTextbox("txtFirstName","Abhishek") %>
 </p>
</asp:Content>

Secondly we will go for the Less Easy Method  :
For  this we will make one folder in our MVC Application. We will add one Class and named it as “LabelHelperExtension.cs” as shown in below screen shot.
For this we need to Include one extra Namespace called

using System.Runtime.CompilerServices;”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
namespace PresentationDEMO.LabelHelperExtension
{
 public static class LabelHelperExtension
 {
 public static string DPLabelExtension(this HtmlHelper DPHelper, string target, string text)
 {
 return string.Format("<Label for='{0}'>{1}</Label>", target, text);
 }
 }
}

Now here we are Extending HtmlHelper Class so we need to pass it as a “very first” parameter in our Method.
In current it is passed with the name “DPHelper”.
This is the main difference while creating these Extension in a simple manner and in Less Easy way .
Now below code shows how to use this newely Extended method in View.

<%= Html.DPLabelExtension("lblDPExtension","abhishek A. Sharma") %>

Lets see another example for truncation a string :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Runtime.CompilerServices;

namespace PresentationDEMO.StringTruncateExtender
{
    public static class StringTruncateExtender
    {
        public static string DPTruncate(this HtmlHelper helper, string stringToTruncate, int length)
        {
            if (stringToTruncate.Length <= length)
            {
                return stringToTruncate;
            }
            else {
                return stringToTruncate.Substring(0, length) + "...";    
            }
        }
    }
}

Now how this can be used :

<%= Html.DPTruncate("Abhishek A. Sharma", 8)%>

This will return you “Abhishek” and rest of all string will get truncated.

MVC and IIS

The Deployment of MVC Application is much straight fwd.. as far as Virtual directory and Mapping of our Application is concern.

The only twist while deploying the MVC Application because we never have the Extension of Pages while serving to user . This is some what like this “Scheduling/Index/24” etc.

Follow the following steps :

  1. Open the Property window of Virtual Directory (in our case “mvc”).
  1. Click on the Configuration Button.
  2. Now we need to add one new Extension to run MVC Application on IIS.
  3. Now search for “aspnet_isapi.dll” (you can get it easily by selecting .aspx extension and click on “Edit” button)
  4. Now restart the IIS and its done…

In this way we can Deploy MVC Application.

Creating First MVC Application (VS2010)

Creating First MVC Application :

Now just let the Application Open into VS and Hit run. Here we can see the very clean URL in browser and application by default displaying the Home Page of Application.

Now we will Add a new Page in the Application. There is nothing much complicated in doing so. For that we will first add a “Controller” who is actually responsible for the navigating and displaying a particular “View”.

After adding this Scheduling Controller, we are going to add another “View” called Scheduling which will be controlled by Scheduling Controller we have just added in our Application. For that just open the Scheduling Controller and right click and click on “Add View”.

Now to run this Scheduling View and see output, we need to place an Action Method for this View in Scheduling Controller which will return this Scheduling View. Here we need to take care of one thing is that , the name of Action Result Method should be same as that of View we have Added . In our case it is “Scheduling” and “Index” so we have added the method with the name “Scheduling”.

If we have mentioned a different name in to the ActionResult then it will go and Search this View Name in to the Shared Folder and if it is not even there then an Error Page is displayed from Shared Folder.

This Clean and Clear URL all is given by the “Route” which is defined in Global.asax file. User can define his/her choice of URL Route and the page will get displayed accordingly as shown in below screen shot…

 

 

 

 

What is a Model View Controller (MVC) Framework?

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

  1. “Models” in a MVC based application are the components of the application that are responsible for maintaining state.  Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
  2. “Views” in a MVC based application are the components responsible for displaying the application’s user interface.  textboxes, dropdowns and checkboxes .
  3. “Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI.  In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

MVC Flow

One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application.  Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

One of the most Important feature of MVC :

It includes a very powerful URL mapping component that enables you to build applications with clean URLs.  URLs do not need to have extensions within them, and are designed to easily support SEO and REST-friendly naming patterns.

Model View Controller

For example, I could easily map the /products/edit/4 URL to the “Edit” action of the ProductsController class.