神刀安全网

Benefits Of Partial View In MVC 5

Today, in this article you will learn to use Partial View in a different manner in any MVC application. As you know that Partial View is a view that will rendered on a parent view. So, I will show you with the help of this article that how we can render partial view in a different way on a parent view.

Partial Viewcan be a parent view and we can use it as a parent view of any partial view. We can simply pass Model to show data in the partial view or we can send the data in the partial view with the help of AJAX call.

We will use Partial View to show the data as in jQuery UI dialogue and we will put Partial View in a div to show the data. In my Previous article on Paging, Searching, Filtering in MVC 5 with Partial View , we saw that how we can use Partial View to show the data in MVC Grid.

So, let’s get started and learn to use Partial View in MVC Application with the help of following structure:

  • Creating ASP.NET MVC Application
  • Performing Database Operation
  • Working with Web Application

Creating ASP.NET MVC Application

In this section, we will create the MVC application. I am creating MVC 5 application and you can use it on MVC 3 or MVC 4. MVC 5 application can be created through Visual Studio 2013 or Visual Studio 2015. Let’s begin with the following steps:

Step 1:In the Visual Studio 2013, click on “New Project”,

Benefits Of Partial View In MVC 5                                Figure 1: Creating New Project in VS 2013

Step 2:Select the Web from the left pane and click on “ASP.NET Web Application” and enter the app name as “BestMovies”,

Benefits Of Partial View In MVC 5                                Figure 2: Creating Web App in VS 2013

Step 3:Select the MVC Project Template in the next “One ASP.Net” Wizard,

Benefits Of Partial View In MVC 5                                         Figure 3: MVC Template in VS 2013

Performing Database Operation

In this section we will create the database and table for performing data operation so that web application can fetch the data from the database. Start with the following steps:

Step 1:Just Create the database from the following code:

CREATE DATABASE BestMovies    

Step 2:Now run the following script to perform the database operations:

USE [BestMovies]   GO   /****** Object:  Table [dbo].[Actor]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   SET ANSI_PADDING ON   GO   CREATE TABLE [dbo].[Actor](       [ActorInfoId] [int] IDENTITY(1,1) NOT NULL,       [Name] [varchar](50) NULL,       [Age] [int] NULL,       [DOB] [datetime] NULL,    CONSTRAINT [PK_Actor] PRIMARY KEY CLUSTERED    (       [ActorInfoId] ASC   )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   ) ON [PRIMARY]      GO   SET ANSI_PADDING OFF   GO   /****** Object:  Table [dbo].[Movie]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   SET ANSI_PADDING ON   GO   CREATE TABLE [dbo].[Movie](       [ID] [int] IDENTITY(1,1) NOT NULL,       [Name] [varchar](50) NULL,       [Genre] [varchar](50) NULL,       [ReleasedDate] [datetime] NULL,       [Actor] [varchar](50) NULL,       [Actress] [varchar](50) NULL,    CONSTRAINT [PK_Movie] PRIMARY KEY CLUSTERED    (       [ID] ASC   )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   ) ON [PRIMARY]      GO   SET ANSI_PADDING OFF   GO   /****** Object:  Table [dbo].[MovieInfo]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   SET ANSI_PADDING ON   GO   CREATE TABLE [dbo].[MovieInfo](       [MovieInfoId] [int] IDENTITY(1,1) NOT NULL,       [MovieId] [int] NULL,       [Director] [varchar](150) NULL,       [Production] [nvarchar](150) NULL,       [ImdbRating] [decimal](2, 1) NULL,       [FilmfareAward] [int] NULL,       [LeadRole] [varchar](50) NULL,    CONSTRAINT [PK_MovieInfo] PRIMARY KEY CLUSTERED    (       [MovieInfoId] ASC   )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   ) ON [PRIMARY]      GO   SET ANSI_PADDING OFF   GO   SET IDENTITY_INSERT [dbo].[Actor] ON       GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (1, N'Amitabh Bachhan', 73, CAST(N'1942-11-10 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (2, N'Rajesh Khanna', 73, CAST(N'1942-12-29 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (3, N'Shahrukh Khan', 50, CAST(N'1965-02-12 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (4, N'Anil Kapoor', 59, CAST(N'1956-12-24 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (5, N'Aishwarya', 42, CAST(N'1973-12-01 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (6, N'Akshay Kumar', 48, CAST(N'1967-09-09 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (7, N'Dilip Kumar', 93, CAST(N'1922-12-11 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (8, N'Amir Khan', 51, CAST(N'1965-03-14 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (9, N'Farhan Akhtar', 42, CAST(N'1942-01-09 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (10, N'Saif Ali Khan', 45, CAST(N'1970-08-16 00:00:00.000' AS DateTime))   GO   INSERT [dbo].[Actor] ([ActorInfoId], [Name], [Age], [DOB]) VALUES (11, N'Prabhas', 36, CAST(N'1979-10-23 00:00:00.000' AS DateTime))   GO   SET IDENTITY_INSERT [dbo].[Actor] OFF   GO   SET IDENTITY_INSERT [dbo].[Movie] ON       GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (1, N'Sholay', N'Action', CAST(N'1975-08-15 00:00:00.000' AS DateTime), N'Amitabh, Dharmendar', N'Hema Malini')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (2, N'Deewar', N'Action', CAST(N'1979-05-14 00:00:00.000' AS DateTime), N'Amitabh, Shashi', N'Parveen Boby')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (3, N'Zanzeer', N'Action', CAST(N'1973-05-11 00:00:00.000' AS DateTime), N'Amitabh', N'Jaya Bhaduri')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (4, N'Don', N'Action', CAST(N'1978-04-20 00:00:00.000' AS DateTime), N'Amitabh', N'Zeenat Aman')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (5, N'Anand', N'Drama', CAST(N'1971-04-03 00:00:00.000' AS DateTime), N'Rajesh Khanna', N'Sumita Snyal')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (6, N'Bawarchi', N'Drama', CAST(N'1972-06-10 00:00:00.000' AS DateTime), N'Rajesh Khanna', N'Jaya Bhaduri')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (7, N'D D L J', N'Romantic', CAST(N'1995-08-19 00:00:00.000' AS DateTime), N'Shahrukh Khan', N'Kajol')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (8, N'Kuch Kuch Hota Hai', N'Romantic', CAST(N'1998-08-16 00:00:00.000' AS DateTime), N'Shahrukh Khan', N'Kajol')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (9, N'Nayak', N'Action', CAST(N'2001-07-07 00:00:00.000' AS DateTime), N'Anil Kapoor', N'Rani Mukharjee')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (10, N'Taal', N'Drama', CAST(N'1999-08-13 00:00:00.000' AS DateTime), N'Anil Kapoor', N'Aishwarya Rai')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (11, N'Sainik', N'Action', CAST(N'1993-07-10 00:00:00.000' AS DateTime), N'Akshay Kumar', N'Ashwini Bhave')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (12, N'Karma', N'Action', CAST(N'1986-08-08 00:00:00.000' AS DateTime), N'Dilip Kumar', N'Nutan')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (13, N'Sarfarosh', N'Action', CAST(N'1995-08-08 00:00:00.000' AS DateTime), N'Amir Khan', N'Sonali Bendre')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (14, N'Saudagar', N'Action', CAST(N'1999-09-12 00:00:00.000' AS DateTime), N'Dilip Kumar, Raj Kumar', N'Manish Koirala')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (15, N'Three Idiots', N'Drama', CAST(N'2012-09-09 00:00:00.000' AS DateTime), N'Amir Khan', N'Kareena Kapoor')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (16, N'Rowdy Rathore', N'Action', CAST(N'2013-09-10 00:00:00.000' AS DateTime), N'Akshay Kumar', N'Sonakshi Sinha')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (17, N'Baby', N'Action', CAST(N'2015-12-12 00:00:00.000' AS DateTime), N'Akshay Kumar', N'Tapsi')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (18, N'Bhaag Milka Bhaag', N'Biographic', CAST(N'2014-10-10 00:00:00.000' AS DateTime), N'Farhan Akhtar', N'Sonam Kapoor')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (19, N'Phantom', N'Action', CAST(N'2015-08-12 00:00:00.000' AS DateTime), N'Saif Ali Khan', N'Kareena Kapoor')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (20, N'Airlift', N'Action', CAST(N'2016-05-06 00:00:00.000' AS DateTime), N'Akshay Kumar', N'Nimrat Kaur')   GO   INSERT [dbo].[Movie] ([ID], [Name], [Genre], [ReleasedDate], [Actor], [Actress]) VALUES (21, N'Bahubali', N'Action', CAST(N'2015-08-12 00:00:00.000' AS DateTime), N'Prabhas', N'Tamannah Bhatiya')   GO   SET IDENTITY_INSERT [dbo].[Movie] OFF   GO   SET IDENTITY_INSERT [dbo].[MovieInfo] ON       GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (1, 1, N'Ramesh Sippy', N'United Producers   Sippy Films', CAST(8.5 AS Decimal(2, 1)), 5, N'Amitabh Bachhan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (2, 2, N'Yash Chopra', N'Trimurti Films', CAST(8.2 AS Decimal(2, 1)), 3, N'Amitabh Bachhan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (3, 3, N'Prakash Meshra', N'Asha Studios', CAST(7.0 AS Decimal(2, 1)), 2, N'Amitabh Bachhan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (4, 4, N'Chandra Barot', N'Nariman Films', CAST(7.9 AS Decimal(2, 1)), 3, N'Amitabh Bachhan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (5, 5, N'Hrishikesh Mukherjee', N'Digital Entertainment', CAST(8.9 AS Decimal(2, 1)), 5, N'Rajesh Khanna')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (6, 6, N'Hrishikesh Mukherjee', N'Digital Entertainment', CAST(8.0 AS Decimal(2, 1)), 1, N'Rajesh Khanna')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (7, 7, N'Aditya Chopra', N'Yash Raj Films', CAST(8.3 AS Decimal(2, 1)), 3, N'Shahrukh Khan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (8, 8, N'Karan Johar', N'Dharma Productions', CAST(7.8 AS Decimal(2, 1)), 1, N'Shahrukh Khan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (9, 9, N'S. Shankar', N'Sri Surya Movies', CAST(7.8 AS Decimal(2, 1)), NULL, N'Anil Kapoor')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (10, 10, N'Subhash Ghai', N'Mukta Arts', CAST(6.8 AS Decimal(2, 1)), NULL, N'Aishwarya')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (11, 11, N'Sikander Bharti', N'Manish Arts', CAST(6.6 AS Decimal(2, 1)), NULL, N'Akshay Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (12, 12, N'Sikander Bharti', N'Mukta Arts', CAST(7.4 AS Decimal(2, 1)), NULL, N'Dilip Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (13, 13, N'John Matthew Matthan', N'Cinematt Pictures', CAST(8.2 AS Decimal(2, 1)), 2, N'Amir Khan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (14, 14, N'Subhash Ghai', N'Mukta Arts', CAST(6.7 AS Decimal(2, 1)), NULL, N'Dilip Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (15, 15, N'Rajkumar Hirani', N'Vinod Chopra Films', CAST(8.4 AS Decimal(2, 1)), 3, N'Amir Khan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (16, 16, N'Prabhu Deva', N'SLB Films', CAST(5.8 AS Decimal(2, 1)), NULL, N'Akshay Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (17, 17, N'Neeraj Pandey', N'T-Series', CAST(8.2 AS Decimal(2, 1)), 2, N'Akshay Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (18, 18, N'Rakeysh Omprakash Mehra', N'ROMP Pictures', CAST(8.3 AS Decimal(2, 1)), 3, N'Farhan Akhtar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (19, 19, N'Kabir Khan', N'Nadiadwala Grandson Entertainment', CAST(5.6 AS Decimal(2, 1)), NULL, N'Saif Ali Khan')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (20, 20, N'Raja Krishna Menon', N'Abundantia Entertainment', CAST(9.1 AS Decimal(2, 1)), 2, N'Akshay Kumar')   GO   INSERT [dbo].[MovieInfo] ([MovieInfoId], [MovieId], [Director], [Production], [ImdbRating], [FilmfareAward], [LeadRole]) VALUES (21, 21, N'S. S. Rajamouli', N'    Arka Media Works', CAST(8.6 AS Decimal(2, 1)), NULL, N'Prabhas')   GO   SET IDENTITY_INSERT [dbo].[MovieInfo] OFF   GO   ALTER TABLE [dbo].[MovieInfo]  WITH CHECK ADD  CONSTRAINT [FK_MovieInfo_Movie] FOREIGN KEY([MovieId])   REFERENCES [dbo].[Movie] ([ID])   GO   ALTER TABLE [dbo].[MovieInfo] CHECK CONSTRAINT [FK_MovieInfo_Movie]   GO   /****** Object:  StoredProcedure [dbo].[BM_GetActorDetails]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   -- =============================================   -- Author:      Nimit   -- Create date: 04/29/2016   -- Description: get actor info   -- =============================================   CREATE PROCEDURE [dbo].[BM_GetActorDetails]        -- Add the parameters for the stored procedure here       @Name varchar(50)    AS   BEGIN       -- SET NOCOUNT ON added to prevent extra result sets from       -- interfering with SELECT statements.       SET NOCOUNT ON;          -- Insert statements for procedure here       SELECT * FROM Actor WHERE Name = @Name   END      GO   /****** Object:  StoredProcedure [dbo].[BM_GetMovies]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   -- =============================================   -- Author:      Nimit Joshi   -- Create date: 02/19/2016   -- Description: This sp is used to get data   -- =============================================   CREATE PROCEDURE [dbo].[BM_GetMovies]        -- Add the parameters for the stored procedure here       @PageNumber INT ,        @PageSize INT     AS   BEGIN       -- SET NOCOUNT ON added to prevent extra result sets from       -- interfering with SELECT statements.       SET NOCOUNT ON;          -- Insert statements for procedure here       SELECT * FROM dbo.Movie (NOLOCK) ORDER BY ID          END         GO   /****** Object:  StoredProcedure [dbo].[BM_GetMoviesInfo]    Script Date: 4/29/2016 2:47:20 PM ******/   SET ANSI_NULLS ON   GO   SET QUOTED_IDENTIFIER ON   GO   -- =============================================   -- Author:      Nimit Joshi   -- Create date: 04/29/2016   -- Description: This sp is used to get movie info   -- =============================================   CREATE PROCEDURE [dbo].[BM_GetMoviesInfo]       -- Add the parameters for the stored procedure here       @MovieId INT   AS       BEGIN       -- SET NOCOUNT ON added to prevent extra result sets from       -- interfering with SELECT statements.           SET NOCOUNT ON;          -- Insert statements for procedure here           SELECT  m.Name ,                   m.Genre ,                   mi.Director ,                   mi.Production ,                   mi.ImdbRating ,                   mi.FilmfareAward ,                   mi.LeadRole           FROM    Movie m ( NOLOCK )                   INNER JOIN dbo.MovieInfo mi ON m.ID = mi.MovieId           WHERE   m.ID = @MovieId       END   GO   

That’s it for the database section.

Working with Web Application

In this section, we will create the architecture of web application and fetch the data from the database and view the data in Razor View and in the Partial View. We will display the data in the Partial view with the help of jQuery UI dialogue or in any simple div.

So, let’s begin with the following procedure:

Adding Model:

Step 1:In the Solution Explorer, right click on the solution and click on “Add New Project”,

Benefits Of Partial View In MVC 5   Figure 4: Adding New Project

Step 2:Select the “Class Library” and enter the name as “BestMoviesModel”,

Benefits Of Partial View In MVC 5 Figure 5: Adding Class Library Project

Step 3:Now add a class in this project as named “Movie”,

Benefits Of Partial View In MVC 5   Figure 6: Adding Class

Step 4:Update the class code with the help of following code:

namespace BestMoviesModel   {       public class Movie       {           #region Properties           public int Id { get; set; }           public string Name { get; set; }           public string Genre { get; set; }           public DateTime ReleasedDate { get; set; }           public string Actor { get; set; }           public string Actress { get; set; }           #endregion       }          public class MovieInfo       {           #region Properties           public int MovieInfoId { get; set; }           public string Director { get; set; }           public string Production { get; set; }           public decimal ImdbRating { get; set; }           public int FilmfareAward { get; set; }           public string LeadRole { get; set; }           #endregion       }          public class Actor       {           #region Properties           public int ActorInfoId { get; set; }           public string Name { get; set; }           public int Age { get; set; }           public DateTime DOB { get; set; }           #endregion       }   }   

Step 5:Just build the solution.

Adding Core

In this section, we will add the project which will handle the database. Follow the steps below:

Step 1:In the Solution Explorer, right click on the solution and click on “Add New Project” and select “Class Library” as named “BestMoviesCore”

Step 2:Now add a reference of “BestMoviesModel” solution in this project,

Benefits Of Partial View In MVC 5                                                  Figure 7: Adding Reference

Step 3:Now in the “BestMoviesCore” project, right click on the References and click on “Manage NuGet Packages” and search for “Enterprise Library” and install it in the project,

Benefits Of Partial View In MVC 5                                      Figure 8: Adding Enterprise Library

Step 4:Now just create two folders as named “BL” and “DAL”.

Step 5:Now add a class in the DAL folder as named “MovieDAL” and replace the code with the following code:

namespace BestMoviesCore.DAL   {       public class MovieDAL       {           #region Variable           ///<summary>             /// Specify the Database variable               ///</summary>             Database objDB;           ///<summary>             /// Specify the static variable               ///</summary>             static string ConnectionString;           #endregion             #region Constructor           ///<summary>             /// This constructor is used to get the connectionstring from the config file                 ///</summary>             public MovieDAL()           {               ConnectionString = ConfigurationManager.ConnectionStrings["BestMovieConnectionString"].ToString();           }           #endregion             #region Database Method           public List<T> ConvertTo<T>(DataTable datatable) where T : new()           {               List<T> Temp = new List<T>();               try               {                   List<string> columnsNames = new List<string>();                   foreach (DataColumn DataColumn in datatable.Columns)                       columnsNames.Add(DataColumn.ColumnName);                   Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));                   return Temp;               }               catch               {                   return Temp;               }           }           public T getObject<T>(DataRow row, List<string> columnsName) where T : new()           {               T obj = new T();               try               {                   string columnname = "";                   string value = "";                   PropertyInfo[] Properties;                   Properties = typeof(T).GetProperties();                   foreach (PropertyInfo objProperty in Properties)                   {                       columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());                       if (!string.IsNullOrEmpty(columnname))                       {                           value = row[columnname].ToString();                           if (!string.IsNullOrEmpty(value))                           {                               if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)                               {                                   value = row[columnname].ToString().Replace("$", "").Replace(",", "");                                   objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);                               }                               else                               {                                   value = row[columnname].ToString();                                   objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);                               }                           }                       }                   }                   return obj;               }               catch (Exception ex)               {                   return obj;               }           }           #endregion             #region Movie Details           /// <summary>           /// This method is used to get the movie data             /// </summary>           /// <param name="PageNumber"></param>           /// <param name="PageSize"></param>           /// <returns></returns>           public List<Movie> GetMovieList(int? PageNumber, int? PageSize)           {               List<Movie> objGetMovie = null;               objDB = new SqlDatabase(ConnectionString);               using (DbCommand objcmd = objDB.GetStoredProcCommand("BM_GetMovies"))               {                   try                   {                       objDB.AddInParameter(objcmd, "@PageNumber", DbType.Int32, PageNumber);                       objDB.AddInParameter(objcmd, "@PageSize", DbType.Int32, PageSize);                            using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])                       {                           objGetMovie = ConvertTo<Movie>(dataTable);                       }                   }                   catch (Exception ex)                   {                       throw ex;                       return null;                   }               }               return objGetMovie;           }              ///<summary>             /// This method is used to get movie details by movie id               ///</summary>             ///<returns></returns>             public List<MovieInfo> GetMovieInfoById(int Id)           {               List<MovieInfo> objMovieDetails = null;               objDB = new SqlDatabase(ConnectionString);               using (DbCommand objcmd = objDB.GetStoredProcCommand("BM_GetMoviesInfo"))               {                   try                   {                       objDB.AddInParameter(objcmd, "@MovieId", DbType.Int32, Id);                       using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])                       {                           objMovieDetails = ConvertTo<MovieInfo>(dataTable);                       }                   }                   catch (Exception ex)                   {                       throw ex;                       return null;                   }               }               return objMovieDetails;           }           #endregion             #region LeardRole Details           ///<summary>             /// This method is used to get the movie data                 ///</summary>             ///<returns></returns>             public List<Actor> GetLeadRoleDetails(string Name)           {               List<Actor> objGetLeadRoleActor = null;               objDB = new SqlDatabase(ConnectionString);               using (DbCommand objcmd = objDB.GetStoredProcCommand("BM_GetActorDetails"))               {                   try                   {                       objDB.AddInParameter(objcmd, "@Name", DbType.String, Name);                       using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])                       {                           objGetLeadRoleActor = ConvertTo<Actor>(dataTable);                       }                   }                   catch (Exception ex)                   {                       throw ex;                       return null;                   }               }               return objGetLeadRoleActor;           }           #endregion       }   }   

Step 6:Now add a class in the “BL” folder as named “MovieBL” and replace the code with the following code:

namespace BestMoviesCore.BL   {       public class MovieBL       {           /// <summary>           /// This method is used to get the movie data             /// </summary>           /// <param name="PageNumber"></param>           /// <param name="PageSize"></param>           /// <returns></returns>           public List<Movie> GetMovieList(int? PageNumber, int? PageSize)           {               List<Movie> objGetMovie = null;               try               {                   objGetMovie = new MovieDAL().GetMovieList(PageNumber, PageSize);               }               catch (Exception)               {                   throw;               }               return objGetMovie;           }              ///<summary>             /// This method is used to get movie details by movie id               ///</summary>             ///<returns></returns>             public List<MovieInfo> GetMovieInfoById(int Id)           {               List<MovieInfo> objMovieDetails = null;               try               {                   objMovieDetails = new MovieDAL().GetMovieInfoById(Id);               }               catch (Exception)               {                                   throw;               }               return objMovieDetails;           }              ///<summary>             /// This method is used to get the movie data                 ///</summary>             ///<returns></returns>             public List<Actor> GetLeadRoleDetails(string Name)           {               List<Actor> objGetLeadRoleActor = null;               try               {                   objGetLeadRoleActor = new MovieDAL().GetLeadRoleDetails(Name);               }               catch (Exception)               {                                   throw;               }               return objGetLeadRoleActor;           }       }   }   

Step 7:That’s it with this section. Now build the solution.

Working with Web Application

Now in this section, we will work with the MVC web application and view the data. Start with the following steps:

Step 1:At first, we will add the reference of “BestMoviesModel” and “BestMoviesCore” projects reference in this project.

Benefits Of Partial View In MVC 5                                           Figure 9: Adding Reference in Web

Step 2:Right click on the Models folder and add a class as named “MovieDetails”,

Benefits Of Partial View In MVC 5                                         Figure 10: Adding Class in Models

Step 3:Replace the code with the following code:

using BestMoviesModel;   using System.Collections.Generic;      namespace BestMovies.Models   {       public class MovieDetails       {           /// <summary>           /// get and set the Movies           /// </summary>           public List<Movie> Movies { get; set; }       }   }   

Step 4:Now right click on the Controllers folder and click on Add-> New -> Controller.

Step 5:Now in the wizard select the “MVC 5 Empty Controller”,

Benefits Of Partial View In MVC 5                                         Figure 11: Add Scaffold in MVC 5

Step 6:Enter the controller name as “MovieController”,

Benefits Of Partial View In MVC 5                                         Figure 12: Add Controller in MVC 5

Step 7:Add the following method in the MovieController,

/// <summary>   /// This method is used to get all movies   /// </summary>   /// <param name="PageNumber"></param>   /// <param name="PageSize"></param>   /// <returns></returns>   [HttpGet, ActionName("GetAllMovies")]   public ActionResult GetAllMovies(int? PageNumber, int? PageSize)   {       List<Movie> objMovie = new List<Movie>();       MovieBL objMovieBL = new MovieBL();          if (object.Equals(PageNumber, null))       {           PageNumber = 1;       }       if (object.Equals(PageSize, null))       {           PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["DefaultPageSize"]);          }       objMovie = objMovieBL.GetMovieList(PageNumber, PageSize);          return View("~/Views/Movie/BestMovies.cshtml", new MovieDetails() { Movies = objMovie });   }    

Step 8:Now goto Views-> Movie, right click on it and add view,

Benefits Of Partial View In MVC 5                                         Figure 13: Adding View in MVC 5

Step 9:Enter the view name as “BestMovies”,

Benefits Of Partial View In MVC 5                                               Figure 14: Add View Wizard

Step 10:Add the following code in the view,

@model BestMovies.Models.MovieDetails   @{       ViewBag.Title = "BestMovies";   }      <h2>Best Movies</h2>      <div class="MovieList">       <div id="MoviesGrid">           @Html.Partial("~/Views/Movie/_BestMoviesPartial.cshtml", Model.Movies)       </div>   </div>   

Note:We are passing data to the Partial view to load the Movie data.

Step 11:Now add a Partial View as named “_BestMoviesPartial” in the View-> Movie folder,

Benefits Of Partial View In MVC 5                                      Figure 15: Addding Partial View in MVC 5

Step 12:Now add the following code in this view:

@model List<BestMoviesModel.Movie>      <table class="table-responsive table">       <thead>           <tr>               <th>Name</th>               <th>Genre</th>               <th>Released Date</th>               <th>Actor</th>               <th>Actress</th>           </tr>       </thead>       <tbody>           @if (Model.Count > 0)           {               foreach (var movieItem in Model)               {                   <tr>                       <td>@movieItem.Name</td>                                           <td>@movieItem.Genre</td>                        <td>@movieItem.ReleasedDate.ToShortDateString()</td>                        <td>@movieItem.Actor</td>                        <td>@movieItem.Actress</td>                    </tr>               }           }           else           {               <tr>                   <td>                       No Data Found                   </td>               </tr>           }       </tbody>   </table>   

Step 13:Now build the solution and open the Views-> Shared-> _Layout.cshtml and replace the code with the highlighted code below:

<head>       <meta charset="utf-8" />       <meta name="viewport" content="width=device-width, initial-scale=1.0">       <title>@ViewBag.Title - My Movies Application</title>       @Styles.Render("~/Content/css")       @Scripts.Render("~/bundles/modernizr")      </head>   <body>       <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("Best Movies", "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>                       <li>@Html.ActionLink("Movies", "GetAllMovies", "Movie")</li>                   </ul>                   @Html.Partial("_LoginPartial")               </div>           </div>       </div>       <div class="container body-content">           @RenderBody()           <hr />           <footer>               <p>©@DateTime.Now.Year - Best Movies Application</p>           </footer>       </div>          @Scripts.Render("~/bundles/jquery")       @Scripts.Render("~/bundles/bootstrap")       @RenderSection("scripts", required: false)   </body>   </html>   

Step 14:Now open the “Web.config” file of Web application and add the following two lines in your file:

Adding Key:

<add key="DefaultPageSize" value="25" />   

Adding ConnectionString:

<add name="BestMovieConnectionString" connectionString="Data Source=MCNDESKTOP07;Initial Catalog=BestMovies;User Id = “UserID”;Password=”UserPassword”"      roviderName="System.Data.SqlClient" />   

Step 15:Now run the application and click on the “Movies”,

Benefits Of Partial View In MVC 5                                      Figure 16: Main Page View of MVC

In the next page you will see Movies data,

Benefits Of Partial View In MVC 5                                         Figure 17: Partial View in MVC 5

Partial View with jQuery UI Dialogue

In this section, we will pass the Partial View in the jQuery UI Dialogue. For this please follow the steps below:

Step 1:Add the following method in the “MovieController”

/// <summary>   /// This method is used to get movie information   /// </summary>   /// <param name="MovieId"></param>   /// <returns></returns>   [HttpGet, ActionName("GetMovieInfo")]   public ActionResult GetMovieInfo(string MovieId)   {       List<MovieInfo> ObjMovieInfo = new List<MovieInfo>();       MovieBL objMovieBL = new MovieBL();          ObjMovieInfo = objMovieBL.GetMovieInfoById(Convert.ToInt32(MovieId));          return PartialView("~/Views/Movie/_MovieDetailsPartial.cshtml", new List<MovieInfo>(ObjMovieInfo));   }   

Step 2:Add another Partial View as named “_MovieDetailsPartial” in the Views->Movie folder and add the following code in it:

@model List<BestMoviesModel.MovieInfo>      <ul class="responsive-MovieDetails">       @if (Model.Count > 0)       {           foreach (var item in Model)           {               <li class="UserDetailList"><span class="UserDetailHeader">Director</span><span>@item.Director</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">IMDB Rating</span><span>@item.ImdbRating</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Production</span><span>@item.Production</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Filmfare Awards</span><span>@item.FilmfareAward</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Lead Role</span><span>@item.LeadRole</span></li>                      }       }       else       {           <li class="NoData">No data found</li>       }   </ul>   

Step 3:Add the reference of jQueryUI from the NuGet Package Manager

Benefits Of Partial View In MVC 5                                   Figure 18: Adding jQuery UI NuGet Package

Step 4:Now open “BestMovies.cshtml” and add the following code at the end:

<div class="popupcntr" id="movieInfo_content" style="display: none;" title="Movie Information">       <div class="innerBox">           <div id="MovieDetails"></div>       </div>   </div>   

Step 5:Now open “_BestMoviesPartial.cshtml” and update the code with the highlighted code below:

@model List<BestMoviesModel.Movie>         <table class="table-responsive table">       <thead>           <tr>               <th>Name</th>               <th>Genre</th>               <th>Released Date</th>               <th>Actor</th>               <th>Actress</th>           </tr>       </thead>       <tbody>           @if (Model.Count > 0)           {               foreach (var movieItem in Model)               {                   <tr>                       <td><a href="javascript:void(0)" onclick="GetMovieDetails('@movieItem.Id')">@movieItem.Name</a></td>                                           <td>@movieItem.Genre</td>                        <td>@movieItem.ReleasedDate.ToShortDateString()</td>                        <td>@movieItem.Actor</td>                        <td>@movieItem.Actress</td>                    </tr>               }           }           else           {               <tr>                   <td>                       No Data Found                   </td>               </tr>           }       </tbody>   </table>      <script type="text/javascript">       function GetMovieDetails(MovieId)       {           $('#movieInfo_content').dialog({               dialogClass: 'moviedetail_dialog',               modal: true,               open: function (event, ui) {                   $.ajax({                       url: '@Url.Action("GetMovieInfo", "Movie")',                       dataType: "html",                       data: { MovieId: MovieId },                       type: "GET",                       error: function (xhr, status, error) {                           var err = eval("(" + xhr.responseText + ")");                           toastr.error(err.message);                       },                       success: function (data) {                           $("#divProcessing").hide();                           $('#MovieDetails').html(data);                       },                       beforeSend: function () {                           $("#divProcessing").show();                       }                   });               },               close: function (event, ui) { $('#movieInfo_content').dialog("destroy"); $('#MovieDetails').html(""); },           });       }   </script>   

Step 6:Now add the following css code in the “Site.css”,

.moviedetail_dialog {       padding: 20PX;       background-color: #fbfbfb;       border: 1px solid rgba(0,0,0,0.2);       box-shadow: 0 0 6px black;   }      .ui-widget-header {       display: inline-block;       font-weight: bold;       margin-right: 20px;   }      .moviedetail_dialog button {       display: inline-block;       margin-left: 20px;   }      .responsive-MovieDetails {       list-style: none;       margin-left: -41px;       margin-top: 20px;   }      .responsive-MovieDetails:after {       content: "";       display: table;       clear: both;   }      .UserDetailList {       margin-bottom: 5px;       margin: 0;      }      .UserDetailList:after {       content: "";       display: table;       clear: both;   }      .UserDetailHeader {       width: 118px;       float: left;       font-weight: bold;   }         .UserDetailHeader + span:before {       content: ":";       margin-right: 15px;       position: absolute;       left: -5px;   }      .UserDetailHeader + span {       float: left;       width: calc(100% - 118px);       padding-left: 10px;       position: relative;   }     #ActorContent .responsive-MovieDetails{       border: 1px solid black; padding:2px;       margin-left:0;   }   

Step 7:Now build the solution and run the application. Open the “Movies” page and just click on any Movie Name as shown below:

Benefits Of Partial View In MVC 5                                               Figure 19: View in MVC 5

Step 8:You will show the popup in the main view as shown below:

Benefits Of Partial View In MVC 5                                         Figure 20: Partial View in UI dialogue

Now you can see that we have easily implemented and passed the Partial View in the jQuery UI dialogue.

Note:You have to add script tag of jQuery UI in the _Layout page.

Partial View with DIV Element

In this section we will load the Partial View in a div element. Start with the following steps:

Step 1:Add the following method in the “MovieController”,

/// <summary>   /// This method is used to get actor information   /// </summary>   /// <param name="MovieId"></param>   /// <returns></returns>   [HttpGet, ActionName("GetLeadRoleDetails")]   public ActionResult GetLeadRoleDetails(string Name)   {       List<Actor> ObjActorInfo = new List<Actor>();       MovieBL objMovieBL = new MovieBL();          ObjActorInfo = objMovieBL.GetLeadRoleDetails(Name);          return PartialView("~/Views/Movie/_ActorDetailsPartial.cshtml", new List<Actor>(ObjActorInfo));   }   

Step 2:Add another Partial View as named “_ActorDetailsPartial” and add the following code:

@model List<BestMoviesModel.Actor>      <ul class="responsive-MovieDetails">       @if (Model.Count > 0)       {           foreach (var item in Model)           {               <li class="UserDetailList"><span class="UserDetailHeader">Name</span><span>@item.Name</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Age</span><span>@item.Age</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">DOB</span><span>@item.DOB.ToShortDateString()</span></li>                       }       }       else       {           <li class="NoData">No data found</li>       }   </ul>   

Step 3:Now change the “_MovieDetailsPartial.cshtml” page code with the highlighted code below:

@model List<BestMoviesModel.MovieInfo>      <ul class="responsive-MovieDetails">       @if (Model.Count > 0)       {           foreach (var item in Model)           {               <li class="UserDetailList"><span class="UserDetailHeader">Director</span><span>@item.Director</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">IMDB Rating</span><span>@item.ImdbRating</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Production</span><span>@item.Production</span></li>               <li class="UserDetailList"><span class="UserDetailHeader">Filmfare Awards</span><span>@item.FilmfareAward</span></li>               <li class="UserDetailList">                   <span class="UserDetailHeader">Lead Role</span><span id="MovieLeadRole">@item.LeadRole <a href="javascript:void(0)" onclick="GetActorDetails('@item.LeadRole')"><img src="~/Images/movie_Info.png" /></a></span>                   <div id="ActorContent"></div>               </li>           }       }       else       {           <li class="NoData">No data found</li>       }   </ul>   <script>       //This method is used to edit user location       function GetActorDetails(name) {           $.ajax({               url: '@Url.Action("GetLeadRoleDetails", "Movie")',               dataType: "html",               data: { Name: name },               type: "GET",               error: function (xhr, status, error) {                   var err = eval("(" + xhr.responseText + ")");                   toastr.error(err.message);               },               success: function (data) {                   $("#MovieLeadRole").css("visibility", "hidden");                   $('#ActorContent').html("");                   $('#ActorContent').html(data);                   $('#ActorContent').show();               }           });       }   </script>   

Step 4:Now run the application and click on the Movie Name to show the information,

Benefits Of Partial View In MVC 5                             Figure 21: Loading Partial View in Div Element

Step 5: Now click on the info icon and the newly added Partial View will load in the Div element as shown below:

Benefits Of Partial View In MVC 5                                         Figure 22: Partial View in Div Element

That’s it.

Summary

So far this article describes to show the data in the Partial View and how we can load Partial View in different manner as in jQuery UI Dialogue or in Div Element. Thanks for reading the article. Happy Coding!!

Read more articles on ASP.NET :

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Benefits Of Partial View In MVC 5

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址