Monday, October 31, 2016

Client Side Validation in ASP.NET MVC

Client Side Validation in a MVC:
ASP.NET MVC supports client side validation using jquery. First of all you need to take a reference of two javascript files from Scripts folder, jquery.validate.unobtrusive.js (jquery.validate.min.js and jquery.validate.unobtrusive.min.js is minified files) in your layout file.


@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")



As you can see by default in the layout.cs.html(Master page).





Add the following two settings in <appsettings> section of web.config, if it is not there.

Razor Syntax:



<add key="ClientValidationEnabled" value="true"/>

<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

Enabling client side validation for a specific view:

By Adding Html.EnableClientValidation(true)
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
    Html.EnableClientValidation(true);
}



If you working for a single page without master page then

In


Code change in Global.asax.cs file
protected void Application_Start()
{
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}


BundleConfig.config:
public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.unobtrusive*",
                "~/Scripts/jquery.validate*"));
}

In View Razor code at bottom:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

Step 2:

Note: The order in which scripts are referenced is very important. If the order is not correct than it won’t work.

Example:

Create a a new controller (Assume I have created a Employeee Controller)





Create a model in the Model Folder.





public class Employee


    {


        [Required(ErrorMessage = "Employee Id is Required")]


        public int EmployeeRegistrationId { get; set; }



        public DateTime  StartDate { get; set; }



        [Required(ErrorMessage = "Email is Required")]


        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +


                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +


                             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",


        ErrorMessage = "Email is not valid")]



        public string EmployeeEmailAddress { get; set; }



        [Required(ErrorMessage = "Employee Phone Number is Required")]


        public int EmployeePhoneNumber { get; set; }





        [Required(ErrorMessage = "Employee Password is Required")]


        public string EmployeePassWord { get; set; }
  
    }



Right click on the Controller and Select Add View


@{
    Layout = null;
}
@model Accordion_Menu_MVC.Models.Employee

@{
ViewBag.Title = "Employee Registration Form";
}


<!DOCTYPE html>
<html>
<head>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <div>
            @using (Html.BeginForm())
            {
                     @Html.ValidationSummary(true)
            <fieldset>
               <legend> Employee </legend>
            <div class="editor-field">
                   @Html.EditorFor(model => model.EmployeeRegistrationId)
                   @Html.ValidationMessageFor(model => model.EmployeeRegistrationId)
               </div>
            <div class="editor-label">
                 @Html.LabelFor(model => model.EmployeePhoneNumber)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.EmployeePhoneNumber)
                @Html.ValidationMessageFor(model => model.EmployeePhoneNumber)
            </div>

            <div class="editor-label">
                   @Html.LabelFor(model => model.EmployeeEmailAddress)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.EmployeeEmailAddress)
                @Html.ValidationMessageFor(model => model.EmployeeEmailAddress)
            </div>
                <div class="editor-label">
                    @Html.LabelFor(model => model.EmployeePassWord)
                </div>
                <div class="editor-field">
                    @Html.PasswordFor(model => model.EmployeeEmailAddress)
                    @Html.ValidationMessageFor(model => model.EmployeeEmailAddress)
                </div>
.              <p>
                <input type = "submit" value="Register" />
            </p>
        </fieldset>
            }
        </div>
    </div>
   
</body>
</html>



 Output:


Example 2:
Client Side validations using Data Annotation attribute and jQuery in ASP.Net MVC Razor.
The Client Side validations will be performed using Model class and Data Annotation attributes.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.

As per MSDN, the Data Annotations attributes cause MVC to provide both client and server validation checks with no additional coding required by you. The Data Annotations attributes can be used with the Entity Data Model (EDM), LINQ to SQL, and other data models.
The Required Data Annotation has been specified with a property Error Message with a string value. As the name suggests, this string value will be displayed to the user when the validation fails.

Accordion Menu Using JQUERY IN MVC



Add a new controller. Assume I have added a Home Controller.


 
public ActionResult Index()
        {
            MenuModel ObjMenuModel = new MenuModel();
            ObjMenuModel.MainMenuModel = new List<MainMenu>();
            ObjMenuModel.MainMenuModel = GetMainMenu();            
            ObjMenuModel.SubMenuModel = new List<SubMenu>();
            ObjMenuModel.SubMenuModel = GetSubMenu();

            return View(ObjMenuModel);
        }

        public List<MainMenu>GetMainMenu()
        {
            List<MainMenu>ObjMainMenu = new List<MainMenu>();
            ObjMainMenu.Add(new MainMenu { ID = 1, MainMenuItem = "Telugu Actors", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 2, MainMenuItem = "Telugu Comedians Actors", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 3, MainMenuItem = "Telugu Villian Actors", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 4, MainMenuItem = "Telugu Music Directors", MainMenuURL = "#" });

            return ObjMainMenu;
        }
        public List<SubMenu>GetSubMenu()
        {
            List<SubMenu>ObjSubMenu = new List<SubMenu>();
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "Pawan Kalyan", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "Mahesh Babu", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "Prabhas", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "Jr Ntr", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "Ali", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "Venu Madhav", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "Sapthagiri", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 3, SubMenuItem = "Mani Sharma", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 4, SubMenuItem = "Devi Sri Prasad", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 4, SubMenuItem = "Koti", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 4, SubMenuItem = "Keervani", SubMenuURL = "#" });
            return ObjSubMenu;
        }


Screen Shot:




In Model Add a new class  MenuModel.cs , and write the following code




In Views in Index.cs.html add the following code

<link href="Css/styles.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">  
    $(document).ready(function () {
        $("#accordian h3").click(function () {         
            $("#accordian ul ul").slideUp();          
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
        });
    });
</script>



@using (Html.BeginForm("Index", "Home"))
{
 <div id="accordian">
       <ul>
              <li>
              @{
    foreach (var MenuItem in Model.MainMenuModel)
    {
         var SubMenuItem = Model.SubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);
       <h3><a href="@MenuItem.MainMenuURL"> @MenuItem.MainMenuItem </a></h3>
           if (SubMenuItem.Count() > 0)
              {
                   <ul>
                            @foreach (var SubItem in SubMenuItem)
                            {
                                <li><a href='@SubItem.SubMenuURL'>@SubItem.SubMenuItem</a></li>
                            }
                   </ul>
              }
       }
    }
              </ul>
</div>   
}
<br />
<div  style="text-align:center"><b>dotnetbyudayrajakonda.blogspot.in</b></div>





Output:



Saturday, October 29, 2016

HTTP GET or Post in MVC

In asp.net Web Forms, IsPostBack page  property is used to check if the request is POST or GET.
If IsPostBack Property returns true, then we knows the request is http post. Else the request is GET


In asp.net mvc use Request object Http Method property to check if the request is get or a Post Request






Example

First Let me add a controller.



Give any Name of the controller , I have given it as Home Controller.



Write the below code in the Home Controller as shown below

As we cannot have same Index method name twice so I have used Index_Post and specifying the Action Attribute Index.

Created a new method to check Wheather IsPost() is True or False.




Right click on the controller and Add View--Index.cshtml


and click on Add Button

After hitting the url you can see that IsPostback is false




In Debugging Mode after hitting Enter.You can see that Get  method is been called.





When  you click on Submit button you can see that it is calling the post method.

and the output is




HTTP POST vs HTTP GET (GET Request Vs Post Request)


HTTP stands for Hypertext Transfer Protocol. Http is the most common protocol used for the communication between a web server and a client.

For Example, to request a home page of any site, then you would type the url of that site.

GET:

Data is submitted as a part of url.

It is not secure but fast and quick.

It is good when you want user to bookmark page.

Data is limited to max length of query string.

GET method should not be used when sending passwords or other sensitive information.

It use Stack method for passing form variable.



Get Request is generally used to get the data from the server


    • When you click on a hyperlink
    • When Response.Redirect() statement is executed
    • When you type URL in the address bar and hit enter 



Example :  Now i want to submit the data.

Default.aspx



Login.aspx:



Output:

On Clicking on button


In Url you can see the values:








Output Explanation: Default.aspx has username data which is sent using get method to login.aspx (server).
 In the output of second screen shot we can see there is key (username) value(uday) data as query stirng in the URL which is submitted to login.aspx page and the output(Welcome uday) is show in login.aspx page.


POST

Data is submitted in http request body.

It is more secured but slower as compared to GET.

It use heap method for passing form variable

It can post unlimited form variables.

Data is not visible in the url.


Example:

Default.aspx

Login.aspx



Output:





Output Explanation

we can observe the post method did not send any query string like what we have seen in get method



Post Request is generally used to submit data to the server.
  • A post request is generally issued
  • When you click on submit button
  • When AUTOPOST back  is set to true and when a selection in the Drop Down  List is changed

Example 2 :




Now with in the button click we are retrieving the details the user has submitted , and then we are appending the values the user has entered using query string and redirecting to webform2

Output Screen:


When we are typing the URL and hitting Enter this is GET Request

Now I want to check in Fiddler Web Debugger and check the Type of Request





After Filling the Form Values:





And Then Clicking on Submit Btn

On Clicking on Submit Button then We are Posting the Data



Here the data is send to the server as part of the Body.



Note:


In asp.net Web Forms, IsPostBack page  property is used to check if the request is POST or GET.

If IsPostBack Property returns true, then we knows the request is http post. Else the request is GET


GET
POST
Data will be arranged in HTTP header by appending to the URL as query string
Data will be arranged in HTTP message body.
Data is in query string so user can view the data
Not visible to user
Less secured compared to POST method because data is in query string so it will be saved in browser history and web server logs
Bit safer than GET method because data is not saved in history or web server logs
As data is saved in URL so its saves only 2048 bytes data
Can be used for any amount of data
Can be bookmarked
Can’t bookmarked
Hacking will be easy
Hacking is difficult
Only ASCII character data type allowed
No restrictions. Allows binary data also
Caching is possible
No caching



Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...