Thursday, March 28, 2013

Upload a file in C# and ASP.NET MVC with Razor.

using System.IO;
using System.Web;
using System.Web.Mvc;
using MvcApplication.Models;
namespace MvcApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         return View(new Dummy());
      }
      
      [HttpPost]
      public ActionResult Index(HttpPostedFileBase zip)
      {
         if (zip.ContentLength > 0)
         {
            var fileName = Path.GetFileName(zip.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/" + fileName));
            zip.SaveAs(path);
         }
         return View();
      }
   }
}

 
 

I thought of doing this in combing through some of my old notes.

The form itself:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype =
      "multipart/form-data" }))
{
   @Html.TextBoxFor(x => x.zip, String.Empty, new { type = "file",
         style = "width: 300px;" })
   <button type="submit">go</button>
}

 
 

I am using this hack for a model to make the Razor stuff work. (grumble)

namespace MvcApplication.Models
{
   public class Dummy
   {
      public int? zip { get; set; }
      public Dummy()
      {
         zip = null;
      }
   }
}

No comments:

Post a Comment