In this post we have added the configuration files which are required to setup the project to work with angular.There are three files as mentioned below:1. package.json2. tsconfig.json3. systemjs.config.js

Model binding allows you to map and bind the HTTP request data with a model.

Model binding implicitly goes to work when an action method has parameter.

Model binding can be explicitly invoked using UpdateModel and TryUpdateModel method.

In this article we will discuss if not implicitly how we can trigger Model binding explicitly.

Why Model binding explicitly?

Sometimes there are cases where we need to trigger the model binding process explicitly. The model binding fills the model class with the form values and also outputs ModelState as by-product, that means if the model class has Data Annotation attributes applied for validation, the model binding validates the model properties against Data Annotation attributes and updates ModelState accordingly. If the validation result is success then the ModelState is true else Vice Versa.

So, in short we know we can trigger explicit model binding for filing model object and also to validate model values if Data Annotation attributes are used.

How Model binding explicitly?
MVC provides two methods which accomplished the task of model binding.

UpdateModel

TryUpdateModel

Both the methods perform same task of explicit model binding, only difference is that the UpdateModel method throws exception if ModelState is not valid and TryUpdateModel not.

The above is our model. We have referred this model class in our View. We will rendering controls for the properties of model inside a form. On submit the form will be posted to controller and there we will perform explicit model binding.

In the view, we have referred Register model and rendered a form using BeginForm helper. We have rendered controls for model properties using EditorForModel helper. We have two buttons i.e. submit and reset.

We have wrapped UpdateModel method inside a try block. The UpdateModel throws exception if model state is not valid. When the model state is not valid, the UpdateModel throws exception and in catch block we are returning model with errors to the view.

Why Model Binding ?
The first question came to your mind would be why to use Model binding ? How it will better or facilitate coding. We will understand this with an example.

We have an Employee Registeration form, the employee fill in details and clicks on submit button.
In order to save values enter by employee we post form to server on submit click, then by using Request object or by using FormCollection object we fetch values out of it as shown below:

As we can see in above screenshot we have to write so much of code to fetch 5 values from posted form. Suppose your form has 20 fields, then you have to write possibly 20 lines to get all values, which also involves type casting.
The Model binding makes it easier to get the form values. Lets see how. We must be using a Model in our View.

The left part in the screenshot is out ViewModel and we have referred this ViewModel on our View as shown on right. When the form is posted on submit click, we can accept object of this ViewModel as parameter.

So, as we have seen by just accepting a parameter of class which is reffered on View as ViewModel, all the properties are filled. This is magic of Model binding. It reduces the lines of code and associated TypeCasting and makes it very easy to get posted values.

How Model Binding works ?
The next question on your mind would be How this magic thing works? Lets discuss this.
When we have an action with parameter, the MVC runtime uses a model binder to build the parameter. The MVC runtime uses workhorse as DefaultModelBinder. The Asp.net MVC allows us to have multiple model binders registered in the MVC runtime for different types of model.
In case of EmployeeViewModel object, the default model binder inspects the EmployeeViewModel and finds all the Employee properties available for binding. The default model binder can automatically convert and move values from the request into an EmployeeViewModel object. In simple words, when the model binder sees an EmployeeViewModel has a Name property, it looks for a parameter named "Name " in the request. The model binder uses components known as value providers to search for values in different areas of request. The model binder can look at route data, the query string, the form collection.

Whats more in Model Binding ?
Till now we saw example for complex type i.e. EmployeeViewModel which is a class. Similarly model binding also works with primitive types, collections and complex types. We will see example for each of them.

Lets start it !!

Primitive types:
Primitive types are the basic data types like int, short, long etc. We will also include example for string in this type. Lets have a complete new example. We have a simple form with two controls one accepting Name and other Age.

At the action method we have accepted two parameters having name same as defined inside form on View. When the form is posted the model binder inspects the action method parameters, search them in the request and binds it with value in the request. If the parameter name at the action method and control's name property on view differs then model binding will not work to get the value.

The above screenshot from the Network section of Developer tool. Check the Form Data section, it shows two form values posted Name and Age.

Below screenshot shows how the parameters are send when form is posted.

This sums up the model binding for primitive type. Lets start with collections.

Collections:

In order to demonstrate this example, we will render List of employees on View. The user can udpate values for all of them and on posting form we will bind the list of employees.

The first action method prepares a List of employees and send list to View. The second action method is one to which form will be posted. In this action method we are accepting object of List of type EmpoyeeViewModel. When the form is posted by us after making changes everything will be captured in the list object at client side.

In case of collection the form is posted in above manner with respect to the controls rendered on View. The Model binder detects properties with [0] belongs to same object and [1] belongs to other. So, using the count the model binder is able to bind the collection types.

Instead of using default Model binder, we can create and register multiple model binders for multiple models as per the requirement. We will discuss about Custom Model binding in other article.

Most of the time we implement the validation at server side, i.e. the form is posted to the server and if the model is invalid the response is sent back to the client and user is displayed with error messages.

The same feature can be achieved at client side, that means the form will be validated at client side, before it is posted to the server.

If the form validation passes, the form is posted otherwise the error message is shown.

The form is posted to above action method on submit. In the above method, we have accepted model object as parameter which triggers the model binding and result of model binding is ModelState. When the ModelState is invalid, the model object is returned with the View.

Till now we have seen how to implement the validation Server side. Lets see how to do it client side.

In order to make it work client side we need to make sure following below points.

1. Make sure below two keys are set to true in web.config.

Make sure the keys ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to true in the Web.config file.

2. Do not forget to refer below javascript files in your View or in Layout if View refers Layout.

Once you made sure you followed above two points, the validation will happen on client side on form submission. If the form validation is success then form is posted to the server else error message is shown to user.

In this article we are going to see what to do when JavaScript is disabled on client browser and Remote attribute does not validate the logic.

To understand this article better read Remote Validation article first, we have used same UserName validation scenario in this article.

Remote ValidationWhat’s wrong when JavaScript is disabled?When JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code.

Why JavaScript disabled?

It depends on user to user whether they want JavaScript enable on browser or not. Following are the most common reason to disable JavaScript on browser.

•Speed & Bandwidth

•Usability & Accessibility

•Platform Support

•Security

Why Server side logic?

The server side logic is necessary as client side logic does not work due to any reason it is always safe and good to have server side logic.

The form is posted to the above Action method. In this method we are checking if username is present in database or not. If username is present in database then we are adding an error to ModelState making it invalid and returning the View with model having model error. So, this will show error message against the UserName control.Screenshot:

So it is good practice to have server side validation as backup to client side validation. This is how you can cover up the validation performed by Remote attribute by writing server side logic as well.

The article explains how to perform remote validation and mandatory settings required for remote validation.As an example we are remotely validating username property of user with database. We are considering the username scenario in this article. We are going to validate whether the username entered by the user exist in database or not.First Let us see What is Remote Validation ?Demo

Remote validation allows the application to call the controller actions using client side script.

This is extremely useful when you want to perform a back end query without having to perform a full server postback.

Remote Validation is basically an ajax call to an action method which queries the database to validate username in our case and returns true or false based on validation result.

The above class is our simple ViewModel having three properties. We have applied Remote attribute on UserName property. We need to refer System.Web.Mvc namespace to use Remote attribute. The first parameter supplied is the Action method name i.e. IsValidUserName which will be called remotely. The second parameter supplied is the name of the controller Home in our case. The third parameter is the error message, this message will be shown if the validation fails.This ViewModel we are going to use on our View as below:View:

In the above View, we have referred UserViewModel as model of the View. We have used EditorForModel helper to render controls for the property of the ViewModel. We have also created a submit button.Controller:

We have a simple Controller named HomeController. We have three method inside the controller.The first ActionResult method is used to render the Index view. The second JsonResult method is the method which will be called remotely to validate username. The third ActionResult method is the method where form is posted i.e. Index with HttpPost attribute. The parameter name UserName in the IsValidUserName method should match the property name in the ViewModel, otherwise the parameter value will be null.Service Class:

The service class has methods which interacts with the database. The first method is IsValidUserName which validates whether DB has user with same username. The Any Linq function returns a boolean value true if DB has username and Vice Versa, and we return negation of that boolean value. That means if user is present we return false as jSon result concluding validation failure, and if user is not present we return true concluding validation success.Layout:

The layout must contains above three script files. These file are must, without these files remote validation is not possible. As we have referred this Layout on our View, we don't need to specify these scripts on View.Web Config:

We need to have above keys set to true in web.config. If either of these keys are absent or set to false remote validation will not work.How attribute works:When the user enters some text in the control i.e. UserName in our case and clicks outside the onblur event is triggered on which IsValidUserName method is called, based on the validation if the user is not present in the database the validation message is shown on UI. Once the onblur event is triggered on making further changes in the same control, the IsValidUserName method is called as soon as you make change to the existing username entered i.e. (onkeyPress). When the onblur event is triggered for the first time and ajax request is made to the IsValidUserName Method. The screenshot below shows the ajax call details. On subsequent changes to username the ajax request is made on keypress.

The ajax call details you can get under Network tab of develper tool.Points to Remember:

Remote Validation is use to validate user input against database without full postback using ajax call.

The remotely method called should return boolean value as JsonResult.

The three script files must be referred on View or on Layout file i.e. jquery-1.5.1.min.js or higher version, jquery.validate.min.js, and jquery.validate.unobtrusive.min.js.

The web.config must contains keys ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true under appSettings.

The Remote Validation will not work if the Javascript is disabled on the browser.

Also read article at below link which demonstrates how to cover up Remote validation when JavaScript is disabled on browser.

In the above view model we have created an enum named players. We have created one class which has one poperty of type players (i.e. enum). We have used DataAnnotation attribute UIHint to indicate MVC framework the editor template to pick while rendering control for the property. In the above example, we are asking MVC framework to use DropDownList cshtml file under Editor Template folder.View:

In the above EditorTemplate we have rendered a dropdownlist control using the enum. When the view is rendered, the UIHint attribute indicates MVC framework to use EditorTemplate to render the control. The editor templates are created under EditorTemplates folder which is under Shared folder. Thus using EditorTemplates we can render any control for any type of property using EditorForModel or EditorFor HTML helper.Screenshots:

The above textbox is rendered when UIHint attribute is not used. The below screenshot shows the result with using UIHint attribute.

Conclusion:

Thus the editor templates can be used with EditorFor or EditorForModel helpers.

The editor templates can be used to render any type of control for model property.

We have created a IEnumerable property of type HttpPostedFileBase to support multiple uploads. The HttpPostedFileBase type property contains file stream and file information when posted to the controller action.View:

We have referred the above View model in the view. We have used TextBoxFor helper to render file control using model binding. We have used htmlAttribute object to set multiple property of control to true which allows to select multiple files. We have created a form using BeginForm helper. We have also created a submit button. When form is submitted the files are posted to UploadMultipleFiles action method of FileUpload controllerController:

We have accepted the object of our View model as a parameter. This object has the posted files. The File property of the FileUploadViewModel class is iterated for multiple files and each file is saved to database using SaveFileDetails method.Service:

In this article we are concentrating on two ways by which we can call stored procedure using entity framework.

Entity Framework performs below expectation when fetching large data, so often we use stored procedure to fetch data.

In the application where one has used entity framework, one can use entity framework itself to call stored procedure.

DemoLets see what are these two ways:Way 1:This is probably the simplest method to call a stored procedure with minimal effort.We have created a simple stored procedure which fetches the registered user to the application. The stored procedure looks like below:

In the above image above is the stored procedure and below is the result that stored procedure returns.

In the above code, we have created a data context object. We have used ExecuteStoreQuery method of data context to fetch the data. The method accepts a parameter which is the name of the stored procedure to call. We are retuning list of type Register class which maps to the Register table in database whose data we are retreiving using stored procedure.Way 2:In this method, we first add stored procedure to the .edmx file. The function inport for the stored procedure is created, function import creates a function which uses the stored procedure.Step 1: Adding stored procedure to EFOpen the edmx file, right click on it, a dialog box will appear as shown below:

Click on Update Model from Database option which will open another dialog box as shown below:

Select the stored procedure and click the Finish button. This will add the stored procedure to the solution or to the edmx file.

In the above image you could see RegisteredUsers added under Stored Procedures folder.Step 2:In this step we will see how to add funtion import for the stored procedure.Right click on the stored procedure added, this will open a window as shown below:

click on the Add Function Import option, this will open another window as shown below:

The function import name field is pre populated, you can give the function name you want, the stored procedure dropdown has the stored procedure for which you want to add function import.

Select the Entities radio button and select the entity to which you want to map the stored procedure. The stored procedure will return the result of the selected entity type. On clicking ok the funtion import will be created for stored procedure.

The preceding code snippet creates a database object, db, with the title HTML5DB, a version number of 1.0, along with a description and approximate size and callback function in later one.
We need to pass basic four arguments to the openDatabase method and callback function if needed.

Database name

Version number

Text Description

Size (Approx)

Callback

The callback function is called when the database is being created. The return value from the openDatabase method contains the transaction methods needed to perform SQL operations (queries) on database.If you try to open a database that doesn’t exist, the API will create it on the fly for you. You also don’t have to worry about closing databases.SizeThe default database size is 5MB for borwsers. The Safari browser shows prompt if user tries to create database exceeding the default database size.

VersionThe version number is required argument to openDatabase. You can change or update version of database using changeVersion method.Using this method we can know which version of database user is using and then we can upgrade. The changeVersion method is supported only in chrome and opera.

Transaction

In very simple words Transaction is a single unit of work. If a transaction is successful, all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be canceled or rolled back, then all of the data modifications are erased. The ability to rollback if some error occurs is why we use transaction for executing sql queries. There are also error ans success callbacks on the transaction, so you can manage errors.

In the preceding code snippet we have used transaction and used executeSql method inside transaction. The above SQL query creates a table EMPLOYEE.executeSql methodThe executeSql method is used to execute a SQL query on database.The executeSql method takes four arguments:
1. a string query.2. an array of strings to insert the values for place holders in string query.3. success callback function.4. failure calback function.
Its a good practice to use SQL quesries or executeSql method inside transaction.Query to Create Table

The preceding code snippet creates a table EMPLOYEE with id and name as parameter. We have also defined callback functions for success and failure of executeSql method.
You can check chrome's developer tool to verify the Database and Table creation. You can verify this under Resources tab.

We have created EMPLOYEE table under HTML5DB database. We can verify the table created under Web SQL.

The preceding code snippet inserts a record in the EMPLOYEE table.
Suppose we want to capture the table data to insert from external source, then we can use the second parameter i.e. inserting the values in the table supplying values to the placeholder defined in the query.

In the preceding code snippet we have defined placeholders in the query. We are then passing values to the placeholder to insert data into the table. The executeSql method's second argument maps the field data to the query. id and name are external variables, and executeSql maps each item in the array argument to the “?”s.Display Records

In the preceding code snippet we have used select query to select all the records from the table and displayed on UI. We have created a UL element and then appened LI elements to UL element.
We need to use the column name after the item object to access the value of that column.For ExampleIn order to get name column's value we should use it like below:

Storage EventsWhenever the data stored in localStorage or sessionStorage changes, the browser triggers a storage event on any other Window objects to which that data is visible (but not on the window that made the change). If a browser has two tabs open to pages with the same origin, and one of those pages stores a value in localStorage, the other tab will receive a storage event. Remember that localStorage is scoped to the top-level window, so storage events are only triggered for localStorage changes when there are frames involved. Also note that storage events are only triggered when storage actually changes. Setting an existing stored item to its current value does not trigger an event, nor does removing an item that does not exist in storage.Register a handler for storage events with addEventListener() (or attachEvent() in IE). In most browsers, you can also set the onstorage property of the Window object, but at the time of this writing, Firefox does not support that property.The event object associated with a storage event has five important properties (they are not supported by IE8, unfortunately):

key - The name or key of the item that was set or removed. If the clear() method was called, this property will be null.

newValue - Holds the new value of the item, or null if removeItem() was called.

oldValue - Holds the old value of an existing item that changed or was deleted, or null if a new item was inserted.

storageArea - This property will equal either the localStorage or the sessionStorage property of the target Window object.

url - The URL (as a string) of the document whose script made this storage change.