Menu

Saturday 20 September 2014

Prevent Partial view to access directly in MVC


About:


As I discussed in earlier blog post, PartialView is mostly used as a type of user control. So, The partial view result should be used in other pages like a child Request and it should not be accessible by direct Route Url.

By Default, PartialViewResult controller will be accessible through Route Url. But, you can restrict or prvent access by just adding a one attribute above to that controller action method named as “[ChildActionOnly]”.

Example:


Now, you can check it out by the example, Just add the below lines of code in the controller action method in sample MVC application.

    public class DemoController : Controller
    {
        /// 
        /// Demo Partial Result
        /// 
        /// 
        public ActionResult DemoPartialResult()
        {
            return PartialView("_Demo");
        }
    }


Now, you create a partial view named as "_Demo.cshtml" with the template as "Empty (without model) " than add any sample text in that parital view.

Now, If you run the application it would accessible like the below.



But, If you add the attribute named as “[ChildActionOnly]” then it does not allow us to access directly from the URL. The code block looks like the below.
        /// 
        /// Demo Partial Result
        /// 
        /// 
        [ChildActionOnly]
        public ActionResult DemoPartialResult()
        {
            return PartialView("_Demo");
        }


Now,If you are trying to access from the URL, It shows the error like the below.


Event, if you can't access the Partial View result action method from ajax call as well.
For Example, The ajax call, you defined in the code like the below.

Now, If you are trying to access that page then you can identify the error in Console window of the browser is as follows.



Conclusion


I hope you got idea how to prevent Partial view Results directly accessing from URL or ajax calls in MVC. Please provide you valuable suggestions and comments if any.


Tuesday 16 September 2014

Visual Studio Key Notes



About:


The Visual studio editor is vast and provides a ton of features. As you are working with visual studio editor, you should know the few features for those helps you a lot to improve the productivity while developing a code.

So, In this post I am going to share with you about some of visual studio key points.
  1.     Features
  2.     Extensions
  3.     Web Essentials
  4.     code snippets
  5.     Help
  6.     Quick Launch
  7.     Refactoring

If you follow the above set of key points in visual studio along with some other, then while writing a code in visual studio is just like a “Communication or discussion between you and visual studio”.

Features:   

  1.     Multiple Browsers set as Default
  2.     Show code Preview tool tip
  3.     Peek Definition

 

Multiple Browsers set as Default:


This feature is really very helpful when you get a chance to work on application, it should support various browsers.Normally, what you should do is run an application in one browser and then copy the same url to another browser to check the browser dependency or UI perspective or some other ways.

But, In Visual studio also provides an option to set “Multiple Browsers” set as default. So you can run the application from visual studio it would open in all browsers. So, The setting should be setup by the following way.



As, per the browser the default browser is “Google Chrome”. Click on Browse with button then the screen should display as below.



Now, Press the Ctrl button and click on “Firefox” then you are able to select two browser types (Just like select multiple list items from list box) and then hit on “Set as Default” button then the resultant screen would display is as follows.



Then close the window and hit a “ Ctrl + F5” button to run the application in two browsers (Google Chrome, Firefox) at a time.




Note: The debugging feature (hit F5) is allow only for single application only. This multiple browser feature would be useful especially to test the GUI display for various browsers.

Show Code preview tool tip:


This feature will be useful when code file contains hundreds of lines, In out of that you are going to search for particular block / piece of code.

So, Normally to achieve the aforesaid requirement, you can use find or method name search for that few key strokes are required,

Instead of that, while just moving the mouse to the vertical scroll bar location as it opens a small glance popup it would show the piece of code and just by clicking on that it would navigates to that particular code location is good right!!!..



Now, you can learn how can you setup this feature in visual studio 2013.

Steps:
  1.     Tools
  2.     Go to Options
  3.     Expand Text Editor
  4.     Expand C#
  5.     Select Scroll Bars
  6.     Go to the Behavior panel
  7.     Select the “Use map mode for vertical scroll bar”

The resultant window screen looks like as follows.




Note: I hope this feature will be helpful when you are working on big screen like extended monitor it would be useful, for normal small laptop screens you can go with existing vertical bar only.

Peek Definition:


As a coding practice and better maintainability will follow code ayers or design patterns. In such a scenario, some of the methods will be inherited from the other classes.

So, In that cases if you want to check the method details with out moving to that particular this Peek definition helps you.

You, just need to place a cursor on any of the method and click on “Alt + F12” it opens small popup contains the method details.

Extensions:


Visual studio supports the extensions which helps to achieve the required things those are not included or in a better way by creating visual studio extensions in (.vsix) file format.

You can install/manage the visual studio extensions from Visual studio itself,By Navigating to Tools and Extensions and Updates.. or else you can directly install extensions from Visual Studio gallery. Some of the extensions are as follows.
  1.     Spell checker
  2.     Go To Definition
  3.     Productivity Power Tools 2013

Spell checker:


Spell checker is one of the great tool as this would be very useful to get rid of some silly/typo mistakes while placing some comments in code level. As placing comments at code level is one of the best thing in code practices.

You can download the tool from this link Spell Checker or else you can directly install from visual studio as well.

Go To Definition:


Visual studio provides so many features like (F12) to go to the definition of code and (Alt+ F12) peek definition to view the code in current location window only with small popup also. Even though this extension provides in a other way to view the code.

If you press and hold the Ctrl key and just mouse over any definition then it turns into a hyper link, By clicking on that link it would navigate to that definition of the code block.

You can download that one from this link Go To Definition

Productivity Power Tools 2013:


The name itself indicates that this tool is very helpful to improve the productivity while writing the code in visual studio 2013. you can call this one as a package instead of extension as this comes with lot of options with customization settings even you can disable / change the setting as you desired.

you can check out description and get the details and download the extension from this link Power Tools.
Installed Extensions in a visual studio having a features like to disable or uninstall the extensions as well.

The Extensions are managed from Visual studio by following this steps.
  1.     Tools
  2.     Go To Extensions and Updates
  3.     select Installed option on left most corner from the opened pop up
  4.     It would show the list of installed extensions
  5.     Now, You can disable or Uninstall the required extension.

Web Essentials:


Web essentials is also one of the best one which will provide great flexibility while writing a code in visual studio editor.

LESS: Less css is kind of dynamic stylesheet language which is very helpful while designing css for any templates or forms. you can get more details from my blog.

ZenCoding: ZenCoding is the one of the greatest feature (at least I feel) in the Web essentials. It helps you a lot to write HTML code in fastest way even visual studio 2013 provides itself a lot of features like (automatically closes (or modify/update) the tag when you write start tag and etc). You can get additional details from my blog.

It also contains a great list of features like TypeScript and etc. you can get more idea about web essentials by checking this link Web Essentials. you can download the web essentials separately based on  visual studio version, For Visual studio 2013 the  link for visual studio gallery  and official site link web essentials.

Code Snippets:


As a developer, Everyone have an idea of some basic C# code blocks like (if.. else, for, foreach, switch,while, creating constructor etc etc..)

But, Just think about it while choosing any one of the aforesaid code block, and just have a count of how many key strokes are used to write that block.

For Example, for writing single if condition like the below it would take minimum of 6 to 7 even visual studio provides automatic feature of closing of braces.

if()
{

}

But, If you have an idea of code snippets, you can achieve that one in only 4 key strokes. By typing “if” and then press “TAB” then visual studio will create if block for you.

The other example is, If you are having a class named as “Customer.cs” then you are going to create constructor for that class. By using code snippet you can just type “ctor” and then hit TAB.

Thats it!!!!... The constructor is ready with the code.

In the similar way for writing try..catch block, just write “try” and then hit TAB.

In the above scenario,The difficult thing is only you just need to have an idea on “ctor” will creates code snippet for constructor block.

Now, The question is how should you know these kind of things.

It is just simple, In any of the code block (c#) or even in .cshtml page block as well, Right Click and then click on “Insert Snippet” then the resultant screen would display like the below.




you can select or review the code snippet names by checking in “Visual C#” or “ASP.NET MVC4” or others and then habituate in the day to day coding style then definitely you could do better code in a productive manner.

Help:


As a developer, you can learn the things in a day to day code by exploring the things. In this manner, Help is needed to learn or understand the things, The same scenario, you could relate with visual studio editor code implementation.

For Example, if you want to get the details about a C# keyword “string”. Instead of searching in google or somewhere else , place a cursor on that keyword and hit “F1”.

The specialty of this search is sensitive framework dependent. Like , If you hit “F1” from the .Net Framework 4.5 application then the msdn help browser will open the result for .Net Framewoek 4.5 only.

The Visual studio provides offline base search also by changing the help preferences from visual studio.
 
 



Quick Launch:


This option is exists generally at right most corner of visual studio. Before discussing with you about this feature, just a few simple questions.
  1.     Have you ever searched in VS menus to for BreakPoints bar to get list of  BreakPoints?
  2.     Have you ever searched in VS menus for Immediate window?
  3.     Have you ever searched in a VS for Solution explorer if its not in right side of editor?

The Quick Launch will helps you a lot to avoid these kind of simple and even some complicated setting with out remembering all those as visual studio is a vast and it contains tons of features.

Bu just typing, some related words in quick launch it would gives a result by clicking on that it would opens the required ones. 
Few examples are mentioned below.
 




Refactoring:


Code Refactoring is also having its own importance while writing a code. Suppose if you have written some block of code as a initial code development. After certain moment, you have noticed that the same block of code will be required at some other location.

Then, Usually what you will do, Remove that block of code, create a method separately with that code then call that method in the required places where as desired.

The whole process will be managed by Visual studio Refactoring option.

You, Just need to do is only select the required code block, Right click and select the Refactoring option.


And then just click on "Extract Method"  then it opens a popup like the below.


Now, By Clicking on "Ok" button  then the code result will display is as follows.




Conclusion:


I hope the provided key notes on visual studio will help you to write code in a smart way with less pain.

Monday 15 September 2014

Partial View Result Return Type in MVC 5 with sample Web application


About:

 

PartialView is the one of  the ActionResult type in MVC. This is also inherited from the ViewresultBase clas.  You can use Partial View is kind of user control in MVC.

So, This PartialView is mostly used for to reduce the repetitive code and also for easy code maintainability.   

 

How Can you Call/Display Partial View:

you can call or display partial view with in the view mainly in four types with the use of html helper methods.

Those are

1. Html.Partial
2. Html.RenderPartial
3. Html.Action
4. Html.RenderAction

I can discuss more about these types in a later post.

Example:

A customer having the details of customer Id, Customer Name and address like Present and Permanent address details.

Key Points to Cover:

  1. Display the customer details using partial view
  2. Edit, update the details using partial view
  3. Create the customer details by using partial view
  4. Delete the customer details by using partial view
  5. How to use Partial view in a view more than once (As I discussed it is kind of user control in MVC)
  6. Strongly typed Partial Views
Note:  This demo is being prepared with Visual Studio 2013 and MVC 5.

you can download the sample project source from the link Download Project

Step 1:

I am going to create new project in Visual Studio 2013 application.
Add a New project from the visual studion, then the displayed screen is as follows.


As, you can see in Visual Studio 2013, you are having only one type of Web application, But if you are selected in VS 2012 template it looks like below.























In this example, I am using Visual Studio 2013 with MVC5.

Step 2:


you can type the Name as “MvcPartialViewResultDemo” and then click on Ok button then the resultant screen displayed as below.




Here, you can select the project template as “MVC” and also select the “Add unit tests”  at the left most corner of the the template then the Test project name displayed as “MvcPartialViewResultDemo.Tests”. 

Its always better practice to select the Unit test project in MVC as it supports TDD (Test Data Driven) approach.

Step 3:

Click on Ok button, then it would create beautiful MVC application with addition of so many features like Login, Register, sample Layout with Responsive design approach (Bootstrap), claim based authentication template (Like login through gmail, facebook etc).  You can simply say that this is the power of visual studio. The displayed project home screen is as follows.


Now, Just click on F5 button, to see the sample MVC application till now what you have created. 



you, can just click on “Restore Down” button or just reduce the browser width then you can identify the resultant responsive design as follows.


So, Sample MVC web application is ready even with out writing single line of code.
Step 4:
The web application solution explorer looks like below.

 

 The highlighted parts of solution explorer as Model, View and Controller, you mainly work on those following components in this example.
Now, you can add one class named as CustomerModel.cs in the Model folder by right click on Model folder then Add and choose the class.
 


By clicking on “class” the template looks like below.

Click on “Add” button then the class will be created. Now, you can replace that class file code with the below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcPartialViewResultDemo.Models
{
    public class CustomerModel
    {
        public int CustmerId { get; set; }
        public string CustomerName { get; set; }
        public CustomerAddress PermanantAddress { get; set; }
        public CustomerAddress PresentAddress { get; set; }
    }
    public class CustomerAddress
    {
        public string DoorNumber { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PinNumber { get; set; }
    }
}

Now, The Customer Model is ready in your application.

You can add a controller named as CustomerController.cs in the controller folder.
Right click on  Controllers folder then Add and the controller


 Click on “Controller” then the screen looks like below.






















This above template provides various types of controllers, In that you can choose the template named as “MVC 5 Controller with read/write actions” then click on “Add” button then another popup will appear its asks you about controller name. So, name it as “CustomerController” like the below.

Now, Just click on “Add” button, It would create CustomerController.cs file.

Are you bit surprised!!! while checking the code as it generates so much of code with all read/write actions. This is the power of template while creating a customer controller what you have chosen.

Note: Even you can define your own level of changes in that controller template by defining custom CodeTemplates (T4 Templates) in your project folder as well.

The CustomerController.cs  code file looks like below.




















Step 6:

Now, you are going to add a partial view which helps to display Address details of a customer. Partial Views can be added with in the parent controller or a shared folder. As a part of coding practice the partial view can be prefixed with “_”.

Add a partial view by following the below steps

  1. Go to Solution Explorer
  2. Views folder
  3. Inside Views folder right click on Shared folder
  4. Click on Add and then View
The resultant screen looks like follows.




Now, click on “View” it opens a popup and apply the changes as per below screen

Changes:

View Name: _CustomerAddressDetails
Template Name: List
Model class: CustomerAddress


select the Create as a Partial view option and then click on “Add” button to creates the partial view. Now, Replace the “_CustomerAddressDetails.cshtml” code with the below code.

@model MvcPartialViewResultDemo.Models.CustomerAddress
@Html.DisplayNameFor(model => model.DoorNumber)
@Html.DisplayFor(model => model.DoorNumber)
@Html.DisplayNameFor(model => model.City)
@Html.DisplayFor(model => model.City)
@Html.DisplayNameFor(model => model.State)
@Html.DisplayFor(model => model.State)
@Html.DisplayNameFor(model => model.PinNumber)
@Html.DisplayFor(model => model.PinNumber)
Step 7:

You can add view to the controller action method named as Index to display the list of all customer details.

 By Clicking on  “Add View” It displays popup and choose the setting as mentioned in the screen.

 Changes:

View name: Index
Template: List (As we are going to display list of customer details)
Model class: CustomerModel

Click on “Add” button then the view will be created  and the displayed screen is as follows.


 Now, update the Index.cshtml with the following design.

@model IEnumerable

@{
    ViewBag.Title = "Index";
}


Customer Details

@Html.ActionLink("Create New", "Create")

@*Headers*@ @*Customer Data*@ @foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.CustmerId) @Html.DisplayNameFor(model => model.CustomerName) @Html.DisplayNameFor(model => model.PresentAddress) @Html.DisplayNameFor(model => model.PermanantAddress)
@Html.DisplayFor(modelItem => item.CustmerId) @Html.DisplayFor(modelItem => item.CustomerName) @Html.Partial("_CustomerAddressDetails",item.PresentAddress) @Html.Partial("_CustomerAddressDetails", item.PermanantAddress) @Html.ActionLink("Edit", "Edit", new { id=item.CustmerId }) | @Html.ActionLink("Details", "Details", new { id = item.CustmerId }) | @Html.ActionLink("Delete", "Delete", new { id = item.CustmerId })
The Index.cshtml file displays as follows.


 Step 8:

Now, open the CustomerController.cs file and add the code as follows to get the list of customer details.

Add a namespace as like below.


using MvcPartialViewResultDemo.Models;
to the CustomerController.cs file and then add the following method to CustomerController.cs file 

public List GetCustomerDetails()
        {
            var customerList = new List();
            for (int i = 1; i <= 2; i++)
            {
                var customer = new CustomerModel
                {
                    CustmerId = i,
                    CustomerName = string.Concat("Customer", i),
                    PermanantAddress = new CustomerAddress()
                    {
                        DoorNumber = string.Concat("Permanent-D.No:4-xx-", i),
                        City = string.Concat("Permanent-City", i),
                        State = string.Concat("Permanent-State", i),
                        PinNumber = string.Concat("Permanent-Pin", i)
                    },
                    PresentAddress = new CustomerAddress()
                    {
                        DoorNumber = string.Concat("Present-D.No:4-xx-", i),
                        City = string.Concat("Present-City", i),
                        State = string.Concat("Present-State", i),
                        PinNumber = string.Concat("Present-Pin", i)
                    }
                };
                customerList.Add(customer);
            }
            return customerList;
        }
and then update the Index action method code as follows. 

 // GET: Customer
        public ActionResult Index()
        {
            var customerDetails = GetCustomerDetails();
            return View(customerDetails);
        }
Now, you can build the application( Ctrl+Shift+B), After a few moments it should be “Build succeeded” then run the application by hitting F5 and then change browser URL (
http://localhost:60385/Customer/Index ) The output screen is as follows. 
















As of now, you are able to display the customer details. Now, you can work on Details of each specific customer.

Step 9:

Go to the CustomerController.cs file and add a “view” for the Action method Details.








The view template is as follows. 


Click on “Add” button and then delete and update the design html is as follows.
@model MvcPartialViewResultDemo.Models.CustomerModel
@{
    ViewBag.Title = "Details";
}

Customer Details

@Html.DisplayNameFor(model => model.CustmerId)
@Html.DisplayFor(model => model.CustmerId)
@Html.DisplayNameFor(model => model.CustomerName)
@Html.DisplayFor(model => model.CustomerName)
@Html.Partial("_CustomerAddressDetails", Model.PermanantAddress) @Html.Partial("_CustomerAddressDetails", Model.PresentAddress)
@Html.ActionLink("Edit", "Edit", new { id = Model.CustmerId }) | @Html.ActionLink("Back to List", "Index")

Step 10:

Now, Add the method GetCustomerById to the CustomerController.cs file is as follows.


public CustomerModel GetCustomerById(int customerId)
        {
            var customerDetails = GetCustomerDetails();
            var customer = (from cust in customerDetails
                where cust.CustmerId == customerId
                select cust).FirstOrDefault();
            return customer;
        }

Now, Update a details action method for CustomController.cs file.

// GET: Customer/Details/5
        public ActionResult Details(int id)
        {
            var customerModel = GetCustomerById(id);
            return View(customerModel);
        }
Build the solution and then hit the “F5” button to see the result by navigating to the URL http://localhost:60385/Customer/Details/1.













Step 11:

Now, Create another partial view to manage the edit/create operations for customer address. The flow for the screen shots is as below. 








By Clicking on "Add" button "_CustomerAddress.cshtml" file would be created and then replace the design with the following below.


@model MvcPartialViewResultDemo.Models.CustomerAddress
    

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.DoorNumber, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.DoorNumber, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.DoorNumber, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.PinNumber, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.PinNumber, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PinNumber, "", new { @class = "text-danger" })
Step 12:

Open CustomerController.cs file and update the Get Edit Action method with the below code.
// GET: Customer/Edit/5
        public ActionResult Edit(int id)
        {
            var customerModel = GetCustomerById(id);
            return View(customerModel);
        }
and then add a view for the Edit method like the below. 



After that, update the Edit.cshtml  with the following html design  


@model MvcPartialViewResultDemo.Models.CustomerModel
@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) { @Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.CustmerId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.CustmerId, new { @class = "form-control", disabled = "disabled", @readonly = "readonly" })
@Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })

Permanent Address:

@Html.Partial("_CustomerAddress", Model.PermanantAddress)

Present Address:

@Html.Partial("_CustomerAddress", Model.PresentAddress)
}
@Html.ActionLink("Back to List", "Index")
Changes:
Disable the customer id
Include the _CustomerAddress.cshtml partial view

Now, update the Post method of Edit action in CustomerController.cs code as below.

Post method of Edit action controller code.

Build the application and hit F5, Navigate to  http://localhost:60385/Customer click on any Edit link of the customer and then update the data like the below.




After updating the details by click on “Save” button it goes to the  post action of Edit method and I have captured the field values while in debugging mode for reference. 
 
As, you observed the Post method of Edit contains two parameters one for CustomerId and another for get the all form control values.

So, FormCollection is being used to get all the control values. As you are used one partial view two times in a form to get the permanent and present address details. The FormCollection values are comes with “,” separator.

Step 13:

Add a view named as “Create.cshtml” from the get action method “Create” in customerController.cs file is as follows.



And then update the design by including Partial views is as follows.


@model MvcPartialViewResultDemo.Models.CustomerModel
@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

CustomerModel


@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @*
@Html.LabelFor(model => model.CustmerId, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.CustmerId, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.CustmerId, "", new { @class = "text-danger" })
*@
@Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })

Permanent Address:

@Html.Partial("_CustomerAddress")

Present Address:

@Html.Partial("_CustomerAddress")
}
@Html.ActionLink("Back to List", "Index")
After that, update the code in Post Create Action method is as follows.

// POST: Customer/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                var customerModel = new CustomerModel
                {
                    CustmerId =  5, //Get the max+1 from customer list
                    CustomerName = collection["CustomerName"],
                    PermanantAddress = new CustomerAddress()
                    {
                        DoorNumber = collection["DoorNumber"].Split(',')[0],
                        City = collection["City"].Split(',')[0],
                        State = collection["State"].Split(',')[0],
                        PinNumber = collection["PinNumber"].Split(',')[0]
                    },
                    PresentAddress = new CustomerAddress()
                    {
                        DoorNumber = collection["DoorNumber"].Split(',')[1],
                        City = collection["City"].Split(',')[1],
                        State = collection["State"].Split(',')[1],
                        PinNumber = collection["PinNumber"].Split(',')[1]
                    }
                };
                // TODO: Add insert logic here
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Now, you are ready with the Create functionality of Customers as well. Just hit F5 and then click on “Create New” customer link then fill the details as you required. 



After entering the details, click on Save button to save the details.  


 
As you noticed in the above image, you would get the all details then you just need to send that customer model object to the database call to save the details.

Step 14:

Add a view named as “Delete.csthml”  from the get action method named as “Delete” in CustomerController.cs file.





And then update the design by including Partial views is as follows.


@model MvcPartialViewResultDemo.Models.CustomerModel
@{
    ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this?


@Html.DisplayNameFor(model => model.CustmerId)
@Html.DisplayFor(model => model.CustmerId)
@Html.DisplayNameFor(model => model.CustomerName)
@Html.DisplayFor(model => model.CustomerName)
@Html.Partial("_CustomerAddressDetails", Model.PermanantAddress) @Html.Partial("_CustomerAddressDetails", Model.PresentAddress)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Update the code in get  Delete  action method is as follows.

 // GET: Customer/Delete/5
        public ActionResult Delete(int id)
        {
            var customerModel = GetCustomerById(id);
            return View(customerModel);
        }

Update the code in post delete action method is as follows.
// POST: Customer/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (id > 0)
                {
                    // TODO: Add delete logic here
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

Build the application and hit F5 button then navigate to the “http://localhost:60385/Customer/Index” and then click on delete link to delete the customer as you desired. The delete customer output is as follows.





As you observed the above image you are getting the customer id then you can perform the database call to delete the customer.

Conclusion:

I hope this above example gives you a brief idea on usage of partial views with a sample application of customer related operations(Details, Display, Create, Edit and Delete) and also you can get some idea how can you create sample application by using MVC.

Please provide your valuable suggestions and feedback if  any.