Tag Archives: HTML

Returning a ViewModel in MVC

Some time it happes when we want to display certain Information in form according to some ID.
This form may contain some Dropdown fields some textboxes or may be other web controls, these controls should display
proper information according to to that ID.
So Instead of writing this code on the Controller class (making controller massy 😦 ) or a smart way could be
creating a ViewModelClass and retutn it.

What a ViewModelClass contains is all the methods and functions which are required to fill all controls according to ID.

Suppose I have a view contains different Dropdowns and textboxes.
I will create a ViewModelClass for this as below :

 public class AddEditScheduleViewModel
    {
        #region Public Properties
        public SelectList ddlClient { get;  set; }
        public SelectList ddlStaff { get;  set; }
        public string txtScheduleDate { get;  set; }
        #endregion 

        #region Contructor
        public AddEditScheduleViewModel()
        {
            ddlClient = new SelectList(ClientsDAL.GetClientList(SessionHandler.LoggedinUserInfo.AgencyID, "02"), "clientID", "entDisplayName");
            ddlStaff = new SelectList(StaffDAL.GetStaffList(SessionHandler.LoggedinUserInfo.AgencyID), "staffID", "staffName");
            txtScheduleDate = DateTime.Now.ToShortDateString();
        }
	#endregion 
     }

Here we have made one Constructor “AddEditScheduleViewModel()” where we have written code to get data for dropdown.

<%=Html.DropDownList("ddlClient",(SelectList)ViewData["ddlClient"], "", new { onChange="return onClientChange(this)" , @Style = "width:65%" })%>
<%=Html.DropDownList("ddlStaff",(SelectList)ViewData["ddlStaff"], "", new { onChange="return onStaffChange(this)", @Style = "width:65%" })%>

This ViewModel may also contains some method Overloads like below :

public AddEditScheduleViewModel(string ScheduleID)
{
    getSchedulDataByID(ScheduleID, "none");
}
public AddEditScheduleViewModel(string ScheduleID,string mode)
{
    getSchedulDataByID(ScheduleID,mode);
}

Now how to use this ViewModelClass and how to call these Overload methods :

public ActionResult AddEditSchedule(string Submit) { 
switch (Submit)
    {
	case "Save":
		AddSchedule(ScheduleID); //Add Edit Schedule Event
		return View(new AddEditScheduleViewModel());
	case "Delete":
		DeleteSchedule(ScheduleID);
		return View(new AddEditScheduleViewModel());
	case "Show Conflict":
		return View(new AddEditScheduleViewModel(Request.Form["hdnConflictSchedID"].ToString()));
	default:
	    //your custom code will go here
    }
}

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
    }
}

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..