Views: View is a user interface. View displays data from the model to the user and also enables them to modify the data. ASP.NET MVC views are stored in the Views folder. Shared folder contains views, layouts or partial views which will be shared among multiple views.
ViewBag: ViewBag is a mechanism to pass data from the controller to the view. To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewBag.
ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below.
// Storing data in ViewBag
ViewBag.EmployeeID = "E101";
// Retrieving data from ViewBag
string strData = ViewBag.EmployeeID;
ViewBag does not provide compile time error checking. For example, if you mis-spell the property name, you wouldn't get any compile time error. You get to know about the error only at runtime.
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
ViewData: ViewData is a mechanism to pass data from the controller to the view. To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewData. ViewData is a dictionary of objects that are stored and retrieved using strings as keys. The syntax of ViewData is very similar to that of ViewState, SessionState, and ApplicationState.
Storing data in ViewData
ViewData["EmployeeID"] = "E101";
Retrieving data from ViewData
string strData = ViewData["EmplyeeID"].ToString();
ViewData["EmployeeID"] = "E101";
Retrieving data from ViewData
string strData = ViewData["EmplyeeID"].ToString();
ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn't get any compile time error. You get to know about the error only at runtime.
Partial Views: In ASP.NET MVC, a partial view is a custom, reusable component created using the same techniques required for creating a HTML view for a particular engine. As a developer, you identify partial views by name and can reference them in a Razor view file in either of two ways: using the Html.Partial method or Html.RenderPartial.
Partial views in mvc are similar to user controls in asp.net webforms. Partial views are used to encapsulate re-usable view logic and are a great means to simplify the complexity of views. These partial views can then be used on multiple views, where we need similar view logic.
If you are using web forms view engine, then the partial views have the extension of .ascx. If the view engine is razor and programming language is c#, then partial views have the extension of .cshtml. On the other hand, if the programming language is visual basic, then the extension is .vbhtml.
Partial views can be added to "Shared" folder or to a specific views folder. Partial views that are in the "Shared" folder are available for all the views in the entire project, whereas partial views in a specific folder are available only for the views with-in that folder.
Difference between html.partial and html.renderpartial
1. The return type of "RenderPartial" is void, where as "Partial" returns "MvcHtmlString"
2. Syntax for invoking Partial() methods in Razor views
@Html.Partial("PartialViewName")
2. Syntax for invoking Partial() methods in Razor views
@Html.Partial("PartialViewName")
3. Syntax for invoking RenderPartial() methods in Razor views
@Html.Partial("PartialViewName")
{ Html.RenderPartial("PartialViewName"); }
@Html.Partial("PartialViewName")
{ Html.RenderPartial("PartialViewName"); }
4. Syntax for invoking Partial() and RenderPartial() methods in webform views
<%: Html.Partial("PartialViewName") %>
<% Html.RenderPartial("PartialViewName"); %>
When would you use Partial() over RenderPartial() and vice versa?
The main difference is that "RenderPartial()" returns void and the output will be written directly to the output stream, where as the "Partial()" method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().
Which one is better for performance?
From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().
<%: Html.Partial("PartialViewName") %>
<% Html.RenderPartial("PartialViewName"); %>
When would you use Partial() over RenderPartial() and vice versa?
The main difference is that "RenderPartial()" returns void and the output will be written directly to the output stream, where as the "Partial()" method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().
Which one is better for performance?
From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().
Strongly Typed Views: Strongly typed views are used for rendering specific types of model objects. By specifying type of data, visual studio provides intellisense for that class. View inherits from ViewPage whereas strongly typed view inherits from ViewPage<T> where T is the type of the model.
Detecting Errors in Views: To enable compile time error checking for views in MVC
1. Open MVC project file using notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.
If you now build the project, you should get all compile-time error, if any.
1. Open MVC project file using notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.
If you now build the project, you should get all compile-time error, if any.
Advantages of using strongly typed views: The following are the advantages of using strongly typed views. We get
1. Intellisense and
2. Compile-time error checking (Compile time error checking is by default false in MVC. We need to make it true). Follow below steps.
1. Open MVC project file using notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.
How to pass data from a controller to a view: There are several ways available to pass data from a controller to a view in an MVC application.
1. ViewBag or ViewData or TempData
2. Dynamic type
3. Strongly typed view
What is a razor page?: Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages. ... Razor is a simple-syntax view engine and was released as part of MVC 3 and the WebMatrix tool set.
What is view engine in MVC?: View Engine is responsible for rendering the view into html form to the browser. By default, Asp.net MVC support Web Form(ASPX) and Razor View Engine. There are many third party view engines (like Spark, Nhaml etc.) that are also available for Asp.net MVC. The namespace for Razor Engine is System.Web.Razor.
Does ASPX view engine supports for TDD?: The web form view engine has syntax that is the same as an ASP.Net forms application. The Razor View Engine uses @ to render server-side content. The ASPX/web form view engine uses "<%= %>" or "<%: %>" to render server-side content. The ASPX view Engine does not support Test Driven Development (TDD).
Does Razor engine support TDD?: Razor Engine supports Test Driven Development (TDD) since it is not dependent on the System.Web.UI.Page class. Web Form Engine doesn't support Test Driven Development (TDD) since it depends on the System.Web.UI.Page class that makes the testing complex. The Razor Engine doesn't support design mode in Visual Studio.
Razor Views: Razor is a mark-up syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
What is the use of Razor View Engine in MVC? : Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without the ASP.NET delimiters: <%= %> . It is a simple-syntax view engine and was released as part of ASP.NET MVC 3. The Razor file extension is "cshtml" for the C# language.
Razor view syntax:
Use @ symbol to switch between c# code and html.
@for (int i = 1; i <= 10; i++)
{
<b>@i</b>
}
{
<b>@i</b>
}
Use @{ } to define a code block. If we want to define some variables and perform calculations, then use code block.
@{
int SumOfEvenNumbers = 0;
int SumOfOddNumbers = 0;
for(int i =1; i<=10; i++)
{
if(i %2 == 0)
{
SumOfEvenNumbers = SumOfEvenNumbers + i;
}
else
{
SumOfOddNumbers = SumOfOddNumbers + i;
}
}
}
int SumOfEvenNumbers = 0;
int SumOfOddNumbers = 0;
for(int i =1; i<=10; i++)
{
if(i %2 == 0)
{
SumOfEvenNumbers = SumOfEvenNumbers + i;
}
else
{
SumOfOddNumbers = SumOfOddNumbers + i;
}
}
}
Use <text> element or @: to switch between c# code and literal text
@for (int i = 1; i <= 10; i++)
{
<b>@i</b>
if (i % 2 == 0)
{
<text> - Even </text>
}
else
{
<text> - Odd </text>
}
<br />
}
Re-written by using @: as shown below.
{
<b>@i</b>
if (i % 2 == 0)
{
<text> - Even </text>
}
else
{
<text> - Odd </text>
}
<br />
}
Re-written by using @: as shown below.
@for (int i = 1; i <= 10; i++)
{
<b>@i</b>
if (i % 2 == 0)
{
@: - Even
}
else
{
@: - Odd
}
<br />
}
@ symbol is used as code delimiter in razor views. However, razor is smart enough to recognize the format of internet email address and not to treat the @ symbol as a code delimiter.
This is my email address<br />
<b>kudvenkat@gmail.com</b>
Use @ symbol to escape @
<b>kudvenkat@gmail.com</b>
Use @ symbol to escape @
I will meet you @@ office
Layout Views: Layout views provide the advantage of maintaining consistent look and feel across all the views in an MVC application. This is similar to the master page in ASP.Net application.
What is _ViewStart.cshtml file?: To associate a view with a layout file, we have to set Layout property on each and every view. This violates DRY (Don't Repeat Yourself) principle and has the following disadvantages
1. Redundant code.
2. Maintenance overhead. To use a different layout file, all the views need to be updated.
Customizing auto generated Views: When we create a controller using MVC 5 Controller with read/write actions or MVC 5 Controller with Views, using Entity Framework, it will create all Controller Action Methods and Classes by referring the Model Class and Data context class. We no need to write single line of code for Index, Create, Details, Delete view. Visual studio will generate minimum code for us. But in some cases when we want to customize the existing views we need to do it carefully because as these are the auto generated code and if sometimes these auto-generated code updated then our custom changes will disappear.
Lets talk about an example: We have an Employee Controller and we have created its all Action methods and View using entity framework. By default it will take Database table column names while rendering the HTML. Below are the customizations we can do it in a partial class so that, if in feature if these are auto-generated our code will not be lost.
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}
public class EmployeeMetaData
{
[StringLength (10,MinimumLength =5)]
[Display(Name = "Employee Name")]
public string Name { get; set; }
[Required]
public string Designation { get; set; }
[Required]
public string Gender { get; set; }
[Required]
[Display(Name = "Date of Join")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Range(typeof(DateTime),"01/01/2010","01/01/2018")]
public DateTime? DateofJoin { get; set; }
[Required]
[Display(Name = "Id Proof Type")]
public string IdProofType { get; set; }
[Required]
[Display(Name = "Id Proof")]
public string IdProof { get; set; }
[Required]
public Nullable<int> Salary { get; set; }
[Required]
public string Active { get; set; }
[Required]
public string Address { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string PhoneNo { get; set; }
[Required]
public string Photo { get; set; }
[Required]
[Display(Name = "Documents Submitted")]
public string DocumentsSubmited { get; set; }
}
How Controller finds a view:
When a MVC URL is requested in the browser it looks the respective view in the following places in the application first. If found then, it renders the respective HTML page else it throughs error as view not found.
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Employee/Index.aspx
~/Views/Employee/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Employee/Index.cshtml
~/Views/Employee/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
~/Views/Employee/Index.aspx
~/Views/Employee/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Employee/Index.cshtml
~/Views/Employee/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
So, from the error message, it should be clear that, MVC looks for a view with the same name as that of the controller action method in the following locations
1. Views/Shared
2. Views/FolderNameMatchingControllerName
1. Views/Shared
2. Views/FolderNameMatchingControllerName
View engines in asp.net MVC:
ASP.Net MVC offers 2 view engines.
1. ASPX
2. Razor
1. ASPX
2. Razor
What is the difference between RAZOR and ASPX view engines?
It mostly, boils down to the syntax. Otherwise there are no major differences between the two. In ASPX view engine, the server side script is wrapped between <% %>, where as in RAZOR we use @. Personally, I prefer using RAZOR views, as it is very easy to switch between HTML and Code.
Depending on the programming language you have chosen, RAZOR views have the extension of.CSHTML or .VBHTML, whereas ASPX views have the extension of.ASPX
It mostly, boils down to the syntax. Otherwise there are no major differences between the two. In ASPX view engine, the server side script is wrapped between <% %>, where as in RAZOR we use @. Personally, I prefer using RAZOR views, as it is very easy to switch between HTML and Code.
Depending on the programming language you have chosen, RAZOR views have the extension of.CSHTML or .VBHTML, whereas ASPX views have the extension of.ASPX
Is it possible, to have both RAZOR and ASPX views in one application?
Yes, when you right click on any controller action method, and select "Add View" from the context menu, you will have the option to choose the view engine of your choice from the "Add View" dialog box.
Yes, when you right click on any controller action method, and select "Add View" from the context menu, you will have the option to choose the view engine of your choice from the "Add View" dialog box.
Is it possible, to use a third party view engine with asp.net mvc?
ASP.NET MVC is designed with extensibility in mind. So, it's very easy to include a third-party view engine as well.
ASP.NET MVC is designed with extensibility in mind. So, it's very easy to include a third-party view engine as well.
Custom View Engines: There are several custom view engines that can be used with asp.net MVC. The following are a few of these custom view engines.
1. Spark
2. NHaml
3. SharpDOM
4. Brail etc....
1. Spark
2. NHaml
3. SharpDOM
4. Brail etc....
For example, if you want to use Spark as the view engine for your asp.net MVC5 project, then install Spark.Web.Mvc5 using NuGet Package Manager.
No comments:
Post a Comment