How To Select Insert, Update And Delete With ASP.NET MVC

How To Select Insert, Update And Delete With ASP.NET MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. In all the above articles I have explained about ASP.Net MVC. Now I think you are clear about ASP.Net MVC and creating simple ASP.Net MVC applications. Whenever we are developing the applications we are related to a database and in the database driven applications we need to perform CRUD operations. On various blogs and sites you will find CRUD operation samples about ASP.Net MVC. But on many the sites I have seen they are all using Entity Framework to perform the CRUD. Since it is the standard, we have to follow it while developing ASP.Net MVC applications instead of using DataSet, Command, Connection, DataAdapter and DataReader. But in many cases we have to use these ADO.Net 2.0 operations. In this  article we will perform all the operations using ADO.NET instead of the ADO.NET Entity Framework. But use these ADO.Net only where you need to else use the ADO.Net Entity Framework only. So let’s start performing CRUD using ADO.Net.

Step 1 : Create the table in your database with the following script.

Step 2 : Now create a new ASP.Net MVC3 Web application with an empty template. This will create one predefined structure with Controllers, Modes and Views folders. All these folders are empty; now we have to add the content to these folders.

Step 3 : As you know, first we have to create a controller so let’s add a new controller with the name Home in the controllers folder. Now our empty controller is ready with an Index method. On the index method we will call the dataset from the database to display the existing Authors in our table. For this we will create a model which will return the dataset, then we will display this data on the view through the Index method of the Home controller. So let’s create one model i.e. class in Models folder with the name SelectModel and write the following code in it to retrieve the data from the database.

In the selectModel class we have one method called GetAllAuthors which returns the dataset of all authors. Now modify your Index method of Home Controller like Entity Framework.

In the above line of code we called the GetAllAuthors method from SelectModel which will return the dataset object and simply we put this dataset in the viewbag. As you know in C# 4.0 we have dynamic programming; you can see one excellent example with viewbag. Here we have written ViewBag.AuthorList which will create dynamically on Author list on runtime for us. Still now we are finished up to calling the dataset and transferring it to the view but still we don’t have any
view so right-click in the Index method and add a new empty view to display our authorlist and write the following markup to display the results.

In the above markup we are displaying our authorlist by creating a HTML table with having Edit and Delete links and lastly having one more ActionLink to add a new author record.

Step 4 : At this stage we are ready with our Index or select operation; now we can add more methods to our Home Controller to perform Edit, Update and Delete operation so let’s start with adding a new record i.e. inserting a new record in the database. In the last step we added an Add New Author ActionLink with Add method so we need to add two more methods in our Home Controller, one for displaying the fields and another for inserting the values; but before that we need to create our model. So add one Model class called InsertModel in your models folder and write the code like below.

The Above code contains some properties with attributes that are used for validation on our view as well as the InsertModel contains Insert method for inserting values in database. Now our InsertModel is ready, so you can add two methods for adding the record in the database add one ADD method with [HttpGet] and a second ADD method with [HttpPost] attributes. These attributes are all of you known. So create two add methods like below.

In the above code, first one add method simply returns the view to take some input from the user and the second add method gets the values from the view and validates it and inserts these values into the database by calling the Insert method of InserModel.

Step 5 : Still now we have only finished Select and Insert operations; now we will see Edit and update. In step3 we have added one edit link bind with AuthorId. On the basis of this AuthorId we will Edit the record and update the record in the database. As in previous steps we need one more Model class so add a Model class called UpdateModel and write the code like below.

In the above code we have properties and one Update method to update the record in the database. In all ModelClasses you can see I’m using ADO.Net only.
Now we have our model class ready so we can add some methods to perform Edit and update operations in our Home Controller so add two more methods called Edit for editing and updating the records like below.

In the above code you can see first the edit method performs some logic to call the specified id record from the database and display this record on the view and the second Edit method performs the update operations.

Step 6 : Now our last operation still remains, i.e. delete; so to delete, add one more model called DeleteModel and write the following code which contains only a delete method to delete the record of the specified AuthorId from the database

In Step3 we have added one ActionLink with delete and given the authorid to it for deleting the specified authorid record from the database. So now we can add one Delete Method in our Home Controller, so add it and write the following code to call the delete method of the DeleteModel to delete the record.

Now we have completed all our operations. Now you can run the application and can perform all the Select, Insert, Update and Delete operations.

Conclusion: In this article we have seen how to add, edit, update and delete the records using ADO.NET in ASP.Net MVC. I hope you enjoyed this article.

How To Creating a Web App Using ASP.NET MVC 4 and AngularJS

How To Creating a Web App Using ASP.NET MVC 4 and AngularJS

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. AngularJS and ASP.NET C# MVC are both MVC frameworks for creating web applications. AngularJS is a JavaScript framework for creating web applications while ASP.NET MVC is a framework for creating web applications using HTML, JavaScript and server side programming language like C# etc. In this tutorial series, we’ll see how to create a web application using both ASP.NET MVC 4 and AngularJS. This tutorial would focus on how to use AngularJS for .net developers.

How To Creating a Web App Using ASP.NET MVC 4 and AngularJS ?

Let’s get started from scratch by creating a ASP.NET MVC 4 empty template project. Once the project has been created it shoud empty without any default code. I did this so that you can get a feel of how to get started from the very scratch and understand how thing really work. So, moving on, first we’ll add a layout to our web application. A layout is like a master page that we have in asp.net web form’s project. In our project’s view directory create a folder called Shared and inside that directory create a file called _Layout.cshtml. Here is how it looks like:

Now there are a couple of things in the above HTML code that would be confusing to a beginner. Let’s take them one by one.

The above code renders the bootstrap related CSS files that we would define in the BundleConfig.cs file in the App_Start folder. Let’s create the BundleConfig.cs class in the App_Start folder. Inside BundleConfig.cs we need to register the routes. Here is how it would look like:

Why do we need to use bundle ? Why not include the files directly like we do in web forms ?

Well, bundling helps to compress the JavaScript file and style sheets into a single file to save bandwidth and that’s why we use it.

Add the following line of code in the Global.asax file in the Application_Start :

Next thing that may look odd in the above code is the @RenderBody(). This is the section of the layout page where the content is rendered each time a new request is received.

For the _Layout.cshtml to be accepted as the layout page for our application we need to define it in another file called _ViewStart.cshtml. Inside Views create a file called _ViewStart.cshtml and add the following code :

Ok now we are all set with the layout code for our web application. Now let’s add a controller inside the Controllers folder called LoginController. Inside the LoginController define a method called ShowDefault which would render a default view.
Here is the ShowDefault method :

Right click on the ShowDefault method and add a view with the same name, ShowDefault. Now a file should get created in the Views/Login/. Add the following code to the ShowDefault.cshtml :

Set the default controller and action method to be called when the app start in the RouteConfig.cs file.

Save the changes and try running the application and you should be able to see the asp.net MVC 4 app in action.

CodeHandbook

Integrating AngularJS and ASP.NET MVC 4

To include AngularJS in your ASP.NET MVC web app, download the AngularJS file and place it in the Scripts folder in your web app. Inside the BundleConfig.cs file include the angular js file too.

Inside the _Layout.cshtml file include the AngularJS script as shown :

Add one more file called app.js in the Scripts folder which would be the root file of our AngularJS application.
Here is how app.js would look like:

Include the app.js file as reference in the _Layout.cshtml page.

Inside the _Layout.cshtml file add the ngApp directive to the HTML tag.

And that’s it, AngularJS has been successfully added to the MVC web app and ready to use.

Using manually the ASP.NET MVC’s client side validation infrastructure

Using manually the ASP.NET MVC’s client side validation infrastructure

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. ASP.NET MVC client side validation is based on the jQuery validation plugin. It can be said that MVC’s client-side validation is an opinionated version of how jQuery validation should work in an ASP.NET MVC project. Despite this, the underlying implementation is fully based on jQuery’s. In this blog post I’ll show you how you can take advantage of this.

mvc

ASP.NET MVC Client Side validation requirements

First, here’s the list of things you need to do to enable client-side validation in an ASP.NET MVC project Make sure your client side code is loading both:

  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure your web.config has the following keys in appSettings with the follwoing values:

These settings can be overridden in a controller, make sure that is not happening. For example this would turn off client side validation if executed inside a controller’s action:

The next requirement is that you use attributes from System.ComponentModel.DataAnnotations in the Model class that is used in view where you want client-side validation enabled.

For example, if we want the Email field to be a valid email, and make the password and email fields required we would create a model like this:

Finally, we have to use the HtmlHelpers that generate the correct markup for all of this to work, and they have to be inside a form, for example

Getting away with using Client Side validation without a model

The last two requirements are actually optional. It is possible to take advantage of client side validation without having to create a model class and annotate it, which can be useful if you only use a couple of parameters (such as in the Login example).

If you inspect the markup that the helpers generate you’ll see that it’s actually pretty simple:

It turns out that to enable client side validation without using the HtmlHelpers and a model you just have to add an input with data-val="true" and then data-val- followed by validation method that you want to apply (e.g. data-val-required), the value of which will be the error message presented to the user (e.g. data-val-required="This is the error message"). This works because the MVC’s “unobtrusive validation” works by looking for inputs that are annotated with data-val attributes.

The data-valmsg-for‘s value is the name (not the id) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field:

This message would then be replaced by any validation error that occurs in the email field, for example “The email is required”. If data-valmsg-replace="false" then the original message will never be replaced. The only consequence of an error is that the span’s class is changed from field-validation-valid to field-validation-error (this happens irrespectively of the value of data-valmsg-replace="false").

Some validation methods have parameters, for example RegularExpression. The way these work is very similar, they just need additional data-val- for their parameters. If you want to validate a text field using a regular expression for 5 to 8 digits, it would look like this:

If you create the markup yourself you can get away without having to create a model for your view. Using the login example from above, your controller action for handling the user logging in could simply be:

You’d have to make any server-side checks on the parameters yourself though.

Here is the list of the System.ComponentModel.DataAnnotation attributes you can use, and their data-val counterparts:

  • Compare
    • data-val-equalto="Error message"
    • data-val-equalto-other="The name of the other field"
  • CreditCard
    • data-val-creditcard="Error message"
  • EmailAddress
    • data-val-email="Error message"
  • MaxLength
    • data-val-maxlength="Error message"
    • data-val-maxlength-max="Maximum length (e.g. 5)"
  • MinLength
    • data-val-minlength="Error message"
    • data-val-minlength-min="Minimum length (e.g. 2)"
  • Range
    • data-val-range="Error message"
    • data-val-range-max="Max value"
    • data-val-range-min="Min value"
  • RegularExpression
    • data-val-regex="Error message"
    • data-val-regex-pattern="The regular expression (e.g. ^[a-z]+$)"
  • Required
    • data-val-required="Error message"
  • StringLength
    • data-val-length="Error message"
    • data-val-length-max="Maximum number of characters"

There are also a few validation methods you can use that don’t seem to have a counterpart in System.ComponentModel.DataAnnotation. In fact you get a list of all the available client side validation methods by typing (for example in chrome) dev tools console: $.validator.unobtrusive.adapters. Here’s the list of the ones that don’t have a matching attribute: date, digits, number, url, length, remote, password.

Securing your ASP.NET MVC Application

Securing your ASP.NET MVC Application

CheapASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. Securing your ASP.NET MVC application ought to be priority number a single each time you begin a brand new net application. Employing the attributes Authorize and ValidateAntiForgeryToken in every single controller and action will be the only method to stay away from any safety holes. In this post I’ll show you the best way to secure your ASP.NET application by implementing the AuthorizeAttribute and ValidateAntiForgeryTokenAttribute classes.

The basics

In the extremely least, you need to add an [Authorize] attribute to every controller or controller Action in case you would like several of the controller actions to be accessible by anonymous users. As an example, you probably want ALL users to possess access for the login and register actions of one’s web application.

By decorating the HomeController using the Authorize attribute (notice I didn’t specify any user part) the application will avert any unauthenticated user from executing any in the actions in this controller.

The following is an instance of decorating a controller action with all the Authorize attribute, you desire to complete this if you only want to restrict access to a few of the actions in a controller instead of all actions.

Safeguarding against Cross-site request forgery attack (CSRF or XSRF)

The Authorize attribute delivers protection which is sufficient in most situations. Nonetheless, there’s security hole with this and therefore it opens your web application for a cross-site request forgery attack. By way of example, right after a user logs into your website the website will concern your browser an authentication token inside a cookie. Every single subsequent request, the browser sends the cookie back for the site to let the web site realize that you are authorized to take what ever action you are taking, so far every thing is very good.

Right here would be the issue with only using the Authorize attribute, let’s say that a user is logged in to your website and then they visit a spam web site by clicking on a hyperlink that points to one more web site which causes a kind post back to your site… this can be negative, your browser will send the authentication cookie to your website generating it seem as when the request came out of your website and initiated by an authenticated user when it genuinely didn’t.

The above situation is known as cross-site request forgery and can be avoided by adding the ValidateAntiForgeryToken attribute offered inside the .NET framework, this attribute is employed to detect regardless of whether a server request has been tampered with.

The initial step would be to add the ValidateAntiForgeryToken attribute to every single Post Action as follows:

The next step is to add the HtmlHelper strategy @Html.AntiForgeryToken() inside the type within your view.

The way the ValidateAntiForgeryToken attribute operates is by checking to view that the cookie and hidden kind field left by the Html.AntiForgeryToken() HtmlHelper essentially exists and match. If they do not exist or match, it throws an HttpAntiForgeryException shown beneath:

“A essential anti-forgery token was not supplied or was invalid”

By adding the ValidateAntiForgeryToken for your controller actions your internet site will likely be prepared to stop CSRF/XSRF attacks.

Implementing Forms Authentication using Active Directory (AD)

Often times you might run across a project where you need to authenticate users of your website using Active Directory credentials, the good news is that you can use the existing “Account” controller to achieve this, only a few modifications are necessary.

When you create a new MVC Web Application project and choose the Internet Application template, the Account controller is added to the project, you can use this controller with AD to authenticate your users. For the Account controller to work with AD we need to remove all Actions but the following:

  • Logon()
  • Logon(LogOnModel model, string returnUrl)
  • LogOff()

Your Account controller should look like the following after you remove the unnecessary Actions such as ChangePassword, Register, etc.

After this, go ahead and clean up the AccountModel as well so the only model class left is the LogOnModel:

Lastly, add the following to the project’s web.config file:

as

Cheap ASP.NET Tips to make ASP.NET MVC application SEO friendly

Cheap ASP.NET Tips to make ASP.NET MVC application SEO friendly

CheapASPNETHostingReview.com | Best and Cheap ASP.NET MVC hosting. In this post I will show you how to make ASP.NET MVC application SEO Friendly. As you know SEO for a website is important. Its like you driving a car without oil. Sure you need the oil.Ok I will go through the most important elements. However, SEO changes all the time and we don’t really know what triggers Google so it’s worth continuing your research afterwards to find out if there are things that are forgotten

Note: While not all WordPress installations are perfect for SEO, it’s usually really good compared to custom installations.

Required on-site SEO optimisations for ASP.NET sites

Sitemap in ASP.NET MVC

seo

Sitemaps are important to tell the search engines exactly what pages you have. Unfortunately you have to make them yourself.

For smaller sites, it’s quite simple. Either you do it manually (which works if you don’t have any dynamic content) or automatically (more on that in a second). You simply make a controller called Sitemap, and makes sure your site responds to calls such as /sitemap and /sitemap.xml .

For bigger sites it’s challenge. If you have a million pages which a previous customer of ours did, you need to run an underlying console job that generates the sitemap.

To help you build it there are a couple of Github projects to help you, and here is an example:
https://github.com/maartenba/MvcSiteMapProvider

Only one <h1> on each page

Each page, when fully rendered, should only have a <h1> tag. The <h1> tag is what the page is about, and should be the main headline.

Canonical URL on pages

It’s in general a very good idea to put a canonical URL on most views. The idea is you tell Google what the real version of the URL is.

A typical example is you have the same page that gets indexed with unique query strings:

  • ?tracking=qwerty
  • ?ref=query

The idea is you then make a canonical URL and refer to itself. So if your view is placed on http://domain.com/page, and you have a version such as http://domain.com/page?ref=query, you should have a canonical URL that is http://domain.com/page.

Remove /home/ from URL in ASP.NET MVC

In a lot of ASP.NET MVC projects, many pages end up having a /home/ url. An example could be /home/contact.

The shorter and more clear URLs, the better. And this is just a quick small thing to update inside the route file.

Prev and next on paginated listings

When you have a paginated result, it’s worth implementing the “prev” and “next”. It’s a way of telling the search engines you are on a paginated result, and what the next and previous pages are.