Wednesday, November 2, 2016

How to Use Partial View in MVC with Example








Partial view is a reusable view, which can be used as a child view in multiple other views. It eliminates duplicate coding by reusing same partial view in multiple places. You can use the partial view in the layout view, as well as other content views.

To start with, let's create a simple partial view for the following navigation bar for demo purposes. We will create a partial view for it, so that we can use the same navigation bar in multiple layout views without rewriting the same code everywhere.


The following figure shows the html code for the above navigation bar. We will cut and paste this code in a separate partial view for demo purposes.

Create New Partial View:

To create a partial view, right click on Shared folder -> select Add -> click on View..

Note :If a partial view will be shared with multiple views of different controller folder then create it in the Shared folder, otherwise you can create the partial view in the same folder where it is going to be used.
In the Add View dialogue, enter View name and select "Create as a partial view" checkbox and click Add.

We are not going to use any model for this partial view, so keep the Template dropdown as Empty (without model) and click Add. This will create an empty partial view in Shared folder.

Now, you can cut the above code for navigation bar and paste it in _HeaderNavBar.cshtml as shown below:
Partial View: _HeaderNavBar.cshtml

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            </ul>
        </div>
    </div>
</div>
Add index and controller as shown below


Index

!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>@ViewBag.Title - My ASP.NET Application</title>
</head>
<body>
@Html.Partial("_HeaderNavBar")
</body>
</html>

Html.Partial():
@Html.Partial() helper method renders the specified partial view. It accept partial view name as a string parameter and returns MvcHtmlString. It returns html string so you have a chance of modifying the html before rendering.
The Html.RenderPartial method writes output directly to the HTTP response stream so it is slightly faster than the Html.Partial method.

The following table lists overloads of the Partial helper method:
Helper MethodDescription
MvcHtmlString Html.Partial(string partialViewName)Renders the given partial view content in the referred view.
MvcHtmlString Html.Partial(string partialViewName,object model)Renders the partial view content in the referred view. Model parameter passes the model object to the partial view.
MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData)Renders the partial view content in the referred view. View data parameter passes view data dictionary to the partial view.
MvcHtmlString Html.Partial(string partialViewName,object model, ViewDataDictionary viewData)Renders the partial view content in the referred view. Model parameter passes the model object and View data passes view data dictionary to the partial view.
Render Partial View Using jQuery Sometimes we need to load a partial view within a model popup at run time, in this case we can render the partial view using J Query element's load method.
<script type="text/jscript">  
$('#partialView').load('/shared/PartialViewExample’); 
</script> 
View Vs Partial View
ViewPartial View
View contains the layout pagePartial view does not contain the layout page
_viewstart page is rendered before any view is renderedPartial view does not check for a _viewstart.cshtml. We cannot place any common code for a partial view within the _viewStart.cshtml page.
View may have markup tags like html, body, head, title, meta etc.The Partial view is specially designed to render within the view and as a result it does not contain any mark up.
Partial view is more lightweight than the view. We can also pass a regular view to the RenderPartial method.
If there is no layout page specified in the view, it can be considered as a partial view. In razor, there is no distinction between views and partial views as in the ASPX view engine (aspx and ascx).
You can load your partial view using j Query load method. It makes ajax request to controller action method and load output in html control like div.
Add div in index.cshtml file as shown in below and add a script to
load output of action method
<div id="partialviews">
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/jscript">    
$(document).ready(function () {       
$("#partialviews").load('/home/GetAddressForjQuery');       
});       
</script>
Add controller action method
public PartialViewResult GetAddressForjQuery(string category)
{
    return PartialView("_address");
}

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.

Kubernetes

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