Avançar para o conteúdo principal

ASP.NET MVC with Entity, Identity and Migrations Part 3 - File Upload

In the third part of this MVC tutorial we add two new controllers and models with the ability to upload files to our web site.

The Room model is pretty simple:

 public class Room {
        [Key]
        public int nr { get; set; }

        [Required(ErrorMessage = "Deve indicar o piso do quarto")]
        public int piso { get; set; }

        [Required(ErrorMessage = "Deve indicar a lotação")]
        public int lotacao { get; set; }

        [Required(ErrorMessage = "Deve indicar o estado do quarto")]
        public bool estado { get; set; }

        [DataType(DataType.Currency)]
        [Required(ErrorMessage = "Deve indicar o preço por dia do quarto")]
        public decimal custo_dia { get; set; }
    }

Just add the controller with Entity framework and that's it.

Next add the Client model:

    public class Client {
        [Key]
        public int ClientId { get; set; }

        [Required(ErrorMessage = "Tem de indicar o nome do cliente")]
        [StringLength(50)]
        [MinLength(5, ErrorMessage = "O nome é muito pequeno")]
        public string nome { get; set; }

        [Required(ErrorMessage = "Tem de indicar a morada do cliente")]
        [StringLength(50)]
        [MinLength(5, ErrorMessage = "Morada muito pequena")]
        public string morada { get; set; }

        [Required(ErrorMessage = "Tem de indicar o código postal do cliente")]
        [StringLength(8)]
        [MinLength(7, ErrorMessage = "O código postal é muito pequeno")]
        [Display(Name = "Código Postal")]
        public string cp { get; set; }

        [DataType(DataType.EmailAddress)]
        public string email { get; set; }

        public string telefone { get; set; }

        [DataType(DataType.Date)]
        [Display(Name = "Data de Nascimento")]
        [Required(ErrorMessage = "Tem de indicar a data de nascimento do cliente")]
        public DateTime data_nascimento { get; set; }
    }

Next add the controller and the view with the Entity framework.

Now in the Client create view add the file upload control, like so:

        <div class="form-group">
            <input type="file" name="fotografia" id="fotografia" class="form-control" /><br />
        </div>

Next alter the form generation line:

@using (Html.BeginForm("Create", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))

This makes a web form with multipart encoding.

To close things up we have to change the function that receives the form to save the file:

 public ActionResult Create([Bind(Include = "ClientId,nome,morada,cp,email,telefone,data_nascimento")] Client client)
        {
            if (ModelState.IsValid)
            {
                db.Clients.Add(client);
                db.SaveChanges();
                //save the file
                HttpPostedFileBase fotografia = Request.Files["fotografia"];
                if (fotografia != null) {
                    string imagem = Server.MapPath("~/Images/") + client.ClientId.ToString() + ".jpg";
                    fotografia.SaveAs(imagem);
                }
                return RedirectToAction("Index");
            }

            return View(client);
        }

Don't forget to create the Images folder.

To be able to see the files uploaded we change the index view adding a new column with the picture:

        <td>
            <img src="@Url.Content(String.Format("~/Images/{0}.jpg",item.ClientId))" width="100" />
        </td>

All this is available on Youtube


And GitHub

Comentários

Mensagens populares deste blogue

New Unity 3D Project

Today I will present a new project that I started. From the post about the car I am building a game with cars, or transportation. The idea is very simple: the player starts with a car and a mission, when he is done with the mission he gets some cash that can be spent buying a new vehicle. Here are some pics: - the car in Unity - the car in Blender - working in the texture - looks great - a wheel - the texture in Gimp - back in Unity testing different materials  like water - and code

Let's make a car in Unity 3D

In this post we will make a simple car in Unity 3D. The Unity 3D physics engine is used in order to give the car a real behavior. This are the steps: [1] - Create a new Project

Single Page App with C# WPF/XAML

 In this post we are going to create a single page app. The app will have multiple pages that get rendered in the main window. We will be using Visual Studio, C#, WPF and XAML. Let's start by creating a new project in Visual Studio of this type: Next, in the MainWindow, we define the interface structure. On the left side we place a menu and on the right side a DockPanel with a Frame in it. The Frame is the element that is used to render de pages content. Now let's add the new pages. In this example I will add two pages. Click in the Solution Explorer with the mouse right button, then choose Add and Page. The project looks like this. The app content goes on the recently create pages. Because this is just an example I will just change the background color and add a small text. Page1 Page2 Finally the code. Back to the MainWindow we need to create the click events on the menu items. So, in the MenuItem line add the click event and pick New Event Handler. If that option doesn't...