Posted on

ASP.NET MVC: SHARED VIEW

The View / Shared folder contains all the visual controls that are to be displayed (used) in different parts of the site: are the old “user controls.” These controls can be called programmatically or called by the site itself automatically.

In this second case, imagine you create the “Student” model. In the View / Shared folder must exist (if not, create them) folders:

  • DisplayTemplates
  • EditorTemplates

If you enter in the 2 folders, 2 view dedicated to the display of “Student” model in two forms of viewing and editing, both named Studente.cshtml, the site will show you your custom control.

Posted on Leave a comment

ASP.NET MVC – First Controller

Visual Studio creates the Controller of Model. Let’s see how.

After creating the Model, Student.cs, in the project, in Visual Studio, position yourself on the Controllers directory. Push the right mouse button and press “Add” -> “Controller”. There appears a mask that offers you to choose the type of controller that you want to create. First on the list it is an empty controller, that is, a class that you have to write independently. The third should be a controller of type “Controller with View, using Entity Framework .” Visual Studio, starting with our Model, creates for us the Controller and view all of the CRUD operations. Choose this type.

Now appears a very important mask. From the top you are asked to choose:

  • Model Class. There is a drop-down menu that is automatically filled with all the classes in the Model (and all the classes in your project). Student choose.
  • Date Class context. You must choose the connection to the database that contains your table. The drop down menu shows all the classes in the project, derived from DbContext class,
  • Check “Generate Views” and “use a Page Layout“.
  • Controller name. Visual Studio there proposes a name one based on the Model you’ve selected. You can change the name, but let the word Controller at the end. (Eg. StudentsController)

Before having to set up the Controller, Visual Studio gives you everything you have written in the models and in DbContext is “right.” If the operation is successful now, in the Controllers directory you find the file StudentsController.cs.

Let’s examine this file. You are inside the class StudentsController derived from Controller.

public class StudentsController : Controller
 {
 private ApplicationDbContext db = new ApplicationDbContext();

// GET: Students
 public ActionResult Index()
 {
 return View(db.Students.ToList());
 }

The class immediately initializes a connection to the database (db).

The first function we see is Index(). It ‘was created automatically and allow us to see the list of our students. Each function of this type is called “Action.” When, in our site we require a list of Students, we launch the Index function of the controller Students according to this path:

http://www.mysite.com/Students/Index

The Index function requires, from the connection to the database, all students (db.Students) and turns them into a list (db.Students.ToList ()). At this point sends our list of students to the view (return View (db.Students.ToList ());) As you can see, there isn’t the name of view but only a generic command “View”. The controller  searches in the list of views, for a view  called exactly like the function (Index) and … we see the students.

In the project, in the directory Views, you will find a folder Student with a list of automatically created files (we’ll analyze the view shortly). In the View directory will find the Shared directory. We can say that this directory contains all the “User Controls” ; all interface items that we intend to use in multiple pages; It contains all of the view that are used by other views. Even the one that in the past called “master page” is located here, in the form of “layout”. Look for the _Layout.cshtml file. This is the website of your graphics (we’ll analyze in detail, soon). Find  this piece of code:

<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>

These are the buttons you see above, when you launch your site. We need to see a new button to call the student page.

Add to this list html:

<li>@Html.ActionLink("My Student", "Index", "Students")</li>

Then we analyze the ActionLink component.

ActionLink (“Text Displayed”, “Name of Action,” Name of the Controller “). So we will have a button that when pushed will take us to http://www.mysite.com/Students/Index page.

Try running the application and perform a login to test that everything is working.

Posted on

ASP.NET MVC. first Model – Code first

In this article we will create something new in our project. We will use the “Code First” approach, that is, “first” will write the code. It seems trite to say, but Visual Studio allows, for example, even the “Database First” approach.

Go into the Model directory and create a new class, for example Student.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MySite.Models
{
 public class Student
 {
 }
}

Add this namespace

using System.ComponentModel.DataAnnotations.Schema;

Our model / class is the representation, through its properties, a table that we will build into the database. First of all, let’s talk to the class as it is called to the table that we are preparing.

[Table("STUDENTS")]
 public class Student
 {
 }

Then we create the properties – fields of the table. Add this namespace:

using System.ComponentModel.DataAnnotations;

our table consists of three fields

[Table("STUDENTS")]
 public class Student
 {
 [Key]
 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
 public int ID { get; set; }

[Required]
 [StringLength(200)]
 [Display(Name = "Name")]
 public string NAME { get; set; }

[StringLength(300)]
 [Display(Name = "Surname")]
 public string SURNAME { get; set; }
 }

The DataAnnotation, written on properties, defining the characteristics of the table fields: ID is the primary key (key), and SQLServer be responsible for assigning the number (DatabaseGeneratedOption.Identity). NAME is a required field (Required) of length 200, the description of which, during a display, it will be “Name” .etc.

Now we must add to DbContext the presence of this table. Open the ApplicationDbContext class and add, as a property, the new table:

public DbSet<Student> Students { get; set; }

Try running the application and perform a login to test that everything is working. Go to the database and built the table complying with his name and the names of the properties of the class.

Posted on

ASP.NET MVC : DATABASE CONNECTION

ApplicationDbContext

In the previous article we introduced the ApplicationDbContext class.

Search it in the project. You should find it within the IdentityModels.cs file. This class derives from the class that derives from IdentityDbContext DbContext.

DbContext is the connection class to a database. The class constructor has as a parameter the name of the connection string that we had previously found in the Web.config file.

public ApplicationDbContext() : base("DefaultConnection")
 {
 }

Let’s think about this information: in the Web.config you can put more connection strings, and then test the application on different databases, changing the parameter above, or you can create an application that connects to different databases by defining more than one DbContext.

Within a DbContext will be referenced all tables in the database we want to use in our application: or rather, all the tables that have constraints between them.

If for example we want to bind to the table of users created by Visual Studio, a second table created by us, the two tables should be part of the same DbContext. But we know nothing of the tables for the management of users created automatically. The class IdentityDbContext contains references to these tables. For this reason, our ApplicationDbContext not derived from DbContext but IdentityDBContext that contains, in fact, a little more information.

As you add tables for your application, you will work on ApplicationDbContext class. For a neater code, you go to create a new file in ApplicationDbContext.cs Models directory and copy, in this class, the ApplicationDbContext code (the only) which is IdentityModels.cs.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
 {
     public ApplicationDbContext()
     : base("DefaultConnection")
     {
     }

     public static ApplicationDbContext Create()
     {
       return new ApplicationDbContext();
     }
 }

Try running the application and perform a login to test that everything is working.

Posted on Leave a comment

asp.net mvc easy easy. Database

The default database

You have created your first project ASP.NET MVC. You can run it through Visual Studio. The site is fully functional and you can register a new user and log in. If you can register and access means “below” the site is already a database. To know where the database and which tables are present for user management, open in Visual Studio, SQL Server Object Explorer and you will see your database under

LocalDB – DefaultConnection

DefaultConnection is the name of the connection string used by your application to connect to the database. If you list the contents of Tables, you see the tables that manage users. If you have created the site using the Framework 4.5.1 or 4.5.2 these tables are 6.

Our SQL Server database

We do not want to work on the default database, but on a SQL Server database on our local machine or network. Create a SQL Server database somewhere. Now we need to connect our website to this database. Open the web.config file and look for the connectionStrings tag. Replace the connection string with a valid connection to your SQL Server database (you will find the connection strings on the Internet). Let the tag name to “DefaultConnection”. Launch the application through Visual Studio.

This is a new database then the user you created before the default database, does not exist here. You must re-register and, at this point, you need to log in. If you now check the contents of your SQL Server database (with Visual Studio SQL Server Object Explorer or with SQL Server Management Studio) you will see that we are also here 6 tables that allow the user management. Created by the site itself.

In your project, in fact, you can find the model tables that allow the user management (in the Models directory), and your site, seeing that the database did not exist any tables, has created them for you. Very comfortable.

From here on, you will create your models, that is, the containers of your data and the site will always attempt to create the tables related to you. This is not an easy process because it does not allow you errors or second thoughts as you create your model. It ‘better to say to the site not to stay from now on to check the consistency of the model – table: you will build your hand models and then your tables of SQL Server. To communicate this to the site, open the file Global.asax.cs, and in Application_Start () function, add this line:

Database.SetInitializer <YourSite.Models.ApplicationDbContext> (null);

Where ApplicationDbContext is the name of the class that connects to the database using the DefaultConnection string. Find this class in the project.

Posted on Leave a comment

asp.net mvc easy easy. Introduction – Part 1

nb. If you decide to work with this technology, whenever you have a doubt or need more details, just go to your favorite search engine and type in your search (with words in English), preceded by these simple words ASP.NET MVC. You will find all the answers.

When we talk about ASP.NET MVC, we mean, in general, the creation of sites with Visual Studio, using C # language and setting the development according to the programming rules MVC.

MVC stands for Model – View – Controller. In practice any old web page is now built using 3 different files; or, the 3 files together make up the page. Two of these files are pure C # code and have the extension .cs, the third is html code and .cshtml extension. In each of the three files is a piece of code. Program in this way will allow you to be more rapid development. For now, you have to trust me.

Let’s take an example. If you look with the browser http://www.miodominio.com/Products/Index page, the site will look for a file called ProductsController.cs (the first of our 3). In ProductsController.cs file exists, at least, the ProductsController class. Within this class, in this file, there is a function called Index. At this point the controller does 2 things: search the site for a file named Index.cshtml. This file (this is the View) contains our html. In some cases the page of the site there are only static phrases. If it is expected that this page contains dynamic data, the controller creates a whole representation of the data from a third file can have any name, for example Item.cs (the Model) and delivers it to Index.cshtml file there finally appears on the browser. Explanation long but it all works in a moment.

From the explanation you understand that there are strict rules about file names: there is then imposed a way of organizing our files, a way to go always the same that will make our maintainable code, ordered and readable by our fellow programmers.

Now open Visual Studio and create the first site in ASP.NET MVC. Find lots of guides on the web but you can also try it by yourself. We analyze the structure of folders that make up the site and see what we can do. In the site you will find surely these three folders:

  •  Controller
  •  Model
  •  View

The controller folder contains Controller file. You can give any name to these files in SomethingController.cs form. Inside the folder, you can create as many subfolders as you want and with any name to reorder better Controller files you create.

The Model Model folder contains files. You can give any name to these files and create as many subfolders as you want.

The Folder View contains the View. Inside this folder must exist for each controller, a subfolder called exactly as the Controller (without Controller.cs). In our examples, we will have a “Products” folder and a “Something” folder. Inside this folder there will be many .cshtml files as there are functions in the Controller file or, rather, the controller functions that you want to be used outside. They must be called exactly as the function. In our example we have:

  •  Controller
    •  ProductsController.cs
    •  SomethingController.cs
  •  Model
    •  Item.cs
  •  View
    •  Products
      •  Index.cshtml
    •  Something

The beauty of this whole management is that Visual Studio does it for you automatically and in a while we will see how.