Show Your Current Age in MVC

Here I am going to show how to make a MVC application to calculate your current Age.

Step 1: Create a view with DOB.aspx name and write the following script.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCTEST1.Models.DOBModel>" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head id="Head1" runat="server">

    <title>DOB</title>

    <style type="text/css">

        .style1

        {

            width: 100%;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table class="style1">

            <tr>

                <td width="25%">

                    &nbsp;

                </td>

                <td>

                    &nbsp;

                </td>

            </tr>

            <tr>

                <td width="25%">

                    <asp:Label ID="Label1" runat="server" Text="Enter DOB"></asp:Label>

                </td>

                <td>

                    <%=Html.TextBox("date1")%>

                </td>

            </tr>

            <tr>

                <td width="25%">

                    <input id="Submit1" type="submit" value="DOB" />

                </td>

                <td>

                    <%: ViewData["Age"] %>

                </td>

            </tr>

            <tr>

                <td width="25%">

                    &nbsp;

                </td>

                <td>

                    &nbsp;

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>

</html>

Step 2: Create a Model as following:

public class DOBModel

{

[DisplayName("DOB")]

public string date1{get;set;}

}

Step 3: Create a Controller with given code.

public ActionResult DOB()

{

ViewData["Age"] = "Enter Your DOB!!!";

return View();

}

// [HttpPost]

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult DOB(DOBModel dob)

{

if (!ModelState.IsValid)

{

return View("DOB", dob);

}

else

{

DateTime old = Convert.ToDateTime(dob.date1);

if (DateTime.Now > old)

{

int age = DateTime.Now.AddYears(-old.Year).Year;

ViewData["Age"] = age;

return View("DOB", dob);

}

else

{

ViewData["Age"] = "Your Dob is older that current time!!!";

return View("DOB", dob);

}

}

 

}

Run your DOB page and see the result..