Tuesday 11 November 2014

Benefits of Html Helpers in Asp.Net MVC

So today i am going to give an overview on Html helpers in Asp.Net MVC . So first questions that stuck our mind are -

 What are Html helpers ?
 Why to use them instead of using simple Html coded controls
 What are their benefits in Asp.Net MVC

Html helpers are very much similar to Asp.Net web controls . But Html helpers are much more lightweight as compared to Asp.net Web forms Server controls . The similarity between server controls in Asp.net webforms and Html helpers in Asp.Net MVC are Viewstate . Means they both contain the ability to hold or update the data on postbacks using ViewStates for each controls .

Main  Benefits Of using Html Helpers in Asp.net MVC

  • MVC Html Helpers contains Overloaded Methods like IPostBackDataHandler that Pre-populate the values of html helpers means it works similar to as viewstates
  • Html Helpers is also having one more advantage It provide inbuilt Validation for html helpers textboxes 
Available HTML Helpers 

There following HTML helpers can be used to render (modify and output) HTML form elements:

  1. BeginForm()
  2. EndForm()
  3. TextArea()
  4. TextBox()
  5. CheckBox()
  6. RadioButton()
  7. ListBox()
  8. DropDownList()
  9. Hidden()
  10. Password()

Sample Code To Demonstrate Use of Html Helpers


ASPX CODE

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()){%>
<p>
<label for="FullName">FullName</label>
<%= Html.TextBox("FullName") %>
<%= Html.ValidationMessage("FullName", "*") %>
</p>
<p>
<label for="Username">Username</label>
<%= Html.TextBox("Username") %>
<%= Html.ValidationMessage("Username", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>

RAZOR CODE

@Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm()){ 
<p>
<label for="FullName">FullName</label>
@Html.TextBox("FullName")  
@Html.ValidationMessage("FullName", "*")  
</p>
<p>
<label for="Username">Username</label>
@Html.TextBox("Username")  
@Html.ValidationMessage("Username", "*")  
</p>
<p>
<label for="Password">Password:</label>
@Html.Password("Password")  
@Html.ValidationMessage("Password", "*")  
</p>
<p>
<label for="Password">Confirm Password:</label>
@Html.Password("ConfirmPassword")  
@Html.ValidationMessage("ConfirmPassword", "*")  
</p>
<p>
@Html.CheckBox("ReceiveNewsletter")  
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>

Advantage of Asp.Net MVC

Asp.net  is a part of .net platform for creating,building, deploying and running web applications using C#,VB etc .we can develop a web application by using Asp.Net Web Form and Asp.Net MVC. Asp.Net MVC is advanced technology that is most widely used nowadays . MVC is a great thing available for developers that makes work of developers easy and more flexible .

MVC stands for Model-View-Controller . MVC separates the code in 3 different things that make the code cleaner , flexible and easy to understand and modify . So Today I am going to tell some of big advantages or some good things that Asp.Net MVC provides as compared to Web-forms . This is not a comparison of Web-forms and MVC this is just overview or advantages or features that Asp.Net mvc provides us

1. Rapid Application Development ( RAD ) :- So first I will start with biggest advantage of Asp.net Mvc and this is the thing that is most in demand in Enterprises and everywhere in development area . This is Rapid application development . Asp.Net MVC provides Database First Approach for developing WebApplications . This approach is used with Scanfolding Technique this technique is like a magic provided in Asp.Net MVC . Scanfolding technique tells if you have designed your database in good manner that means if you have Created Normalized Database with all like Primary keys, foreign keys ,One-many , many-many relationships then you need not to do more effort for developing rest on your application in Asp.Net MVC Rest of things will be created with less efforts using scanfolding . With Asp.Net MVC you can have your simple basic website ready within 1 minute after you created your Database . So that was explanation to RAD in Asp.Net MVC

In Pic below we are choosing MVC5 scanfolding template


Then it automatically generate code for us





2. Partial Layouts :- In Asp.Net we ofter use User controls that were used for code reusability we create a user control then where we require that type of code that we coded in user control we call that user control there . In similar way Partial Layouts is provided in Asp.Net MVC .Partial Layouts are very useful things provided in Asp.Net MVC . Partial Layouts are like Master Pages that we use in Asp.Net web-forms . These are used as master pages or master layouts that can be called in any view in Asp.Net MVC . Like in php we use include ( "partialheader.php" ); to include some header in all pages or some specific pages so instead of writting that code in all pages we call then there . Similar in Asp.Net Web-Forms We use content placeholders and contentplaceholders are placed in Master Pages and when we call these master pages and use then in child forms then code of child forms is placed in content placeholder area In the similar way Partial layout works . The partial layout contains @Renderbody in Razor view then replace the child page or code of  page that is calling it

3. MVC Is  Stateless : Asp.Net was Statefull by using viewstates or sessions but Asp.net MVC is stateless . It will be wrong to say mvc is stateless it would say http is stateless . By stateless i mean there is nothing in http that holds the user session or that record the activity of user when user logged in etc so this was maintained or state was maintained using viewstate and sessions . This was used in asp.net Webforms because they contain server controls that contains viewstate and that postback the values and update viewstates But there is not server controls in Asp.Net MVC So it does not maintain states . It has divided the code in three patterns model-view-controller that handles everything That's why it says MVC is stateless But in actual http is stateless that why MVC is stateless

4. No Events : As we came to know there are no server controls in Asp.Net MVC so there are no events for any control as there are not server controls All this is handled by connection of controllers with views where views hold your html code or designing code and controller hold your logics code .


Difference Between ViewState and Session in Asp.Net

"View State and Session "
  The Two main State Management things used in Asp.net Web applications . We cannot even think of an application without ViewState and Session . So today i decided to gave an overview of what is the difference between viewstate and session why these two terms exist and what are their usage To clearify this difference i am giving some points below

1. So First of all what is a Session ? -- A Session is a Time or a span of time upto which user used that webapplication or for how much session of how much period of time user has used your webapplication will be called session . Session contains some values that will be used throughout the user interaction with the webapplication and used in more than one webpage that user navigate So we can say that it is a variable in simple sense that takes our value from one page to another and Session got distroyed or killed automatically after a particular span or time or it is automatically destroyed or cleared when like user signout of application or when user close the browser

A live example would be a web application where a user login . Each user that logs into your system will have a unique session. We can hold additional data into the session which can be used as the user browses your site. We can hold the username, userrole, userpermissions simply by adding it to the session:


Session[“userrole”] = “programmer”; 
Session[“username”] = “Ageek”; 
Session[“userpermissions"] = “cangotohell”; 

A Session  stores the information on the server side  . It stores the values or it uses server memory for storage of data that it holds in . Session variables will use different new and unique session variables for each different user that logs in to web application . large amount of data can be stored on the session, web sites that have a large amount of traffic not use this method, because it will put a severe load on the server memory.

2. Now What is ViewState ? -- so we are clear with session now comes the turn of viewstate . So ViewState is also used for holding our important data But in case of viewstate data is kept in the single viewstate page . It means viewstate data is not taken from one page to another page in this point it is different from session . 

ViewState is only used to Track to analyse the changes that occur to current page during postbacks of data to pages .The viewstate of page can be viewed if you right click on webpage and then clickon view page source then you will see some code of lines similar to below code --

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=””></input>

If you are having large number of viewstate fields then it will make the postbacks very slow as all viewstate values will be needed to updated during postbacks so it will make the webpage open slower

Data can be written into viewstate like we do in sessions . But it can retain that data only with life cycle of page after that it will be changed or updated .If you closes that page or redirects to another page then viewstate data will be reset .

How to fill data in viewstate and how to access that data 
ViewState[“PreviousPage”] = “http://www.google.com”; 

Retrieving data form ViewState:
string PreviousPage = ViewState[“PreviousPage”].ToString();