1

I am trying to upload file in asp.net MVC but the problem is that I cant get the file from the Request.Files[]

this is the controller side

    [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ValidateAndSignUp(ForCompany newCompany)
    {
        if (ModelState.IsValid)
        {

            company NewCompany = new company();
            TryUpdateModel(NewCompany);
            context.companies.Add(NewCompany);
            string token = new Hash().CalculateMD5Hash(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            if (context.companies.Any(com => com.Email == newCompany.Email.Trim()))
            {
                TempData["message"] = "<div class='error'>This email is already registered " + Request.Files.Count + " </div>";
            }
            else
            {
                uploadFile(Request.Files[0]);
                context.oneTimeAuthenticationTickets.Add(new oneTimeAuthenticationTicket { company_id = NewCompany.company_id, ticket = token, status = "v", DateOfCreation = DateTime.Now});
                context.SaveChanges();
                TempData["message"] = new Email() { To = newCompany.Email, From = "[email protected]", Subject = "New company with this email has been created", Body = "Please follow this <a href = 'http://localhost:49525//Accounts/validateNew/?token=" + token + "'>link</a> to validate your account and to create the first user" }.sendMail();

            }
            return RedirectToAction("signIn", "Accounts");
        }
        else
        {
            return View("signUp", newCompany);
        }
    }

      public void  uploadFile (HttpPostedFileBase file)
      {
          if (file.ContentLength > 0)
          {
              var fileName = Path.GetFileName(file.FileName);
              var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
              file.SaveAs(path);
          }
      }

here is the view side

@model workflow.DataHolders.ForCompany
<link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" />

<div id="Add_container">
    <div class="message">If your company is already registered and  has not been verified or there are no users created, please <a href="@Url.getBaseUrl()/Accounts/VerifyAccount">click</a>  to  configure your account</div>

    @if (!ViewData.ModelState.IsValid)
    {
        <div id="validationMessage">Please Correct The Errors Below</div>
    }


    @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationMessage("CompanyName");
        <span class="field_title">Company Name: </span>
        @Html.TextBox("CompanyName")   

        @Html.ValidationMessage("Email");
        <span class="field_title">Email: </span>
        @Html.TextBox("Email")

        @Html.ValidationMessage("Country");
        <span class="field_title">Country Name: </span>
        @Html.DropDownList("Country", Model.Countries)

        <span class="field_title">About The Company: </span>
        @Html.TextArea("Description")

        <span class="field_title">Choose Company Logo</span>
        @Html.TextBox("Logo", Model.Logo, new { type = "file" })

        <input type="submit" value="Create New Account">


    }
</div>
<div class="get_connected_message">
    <h1>Get Connected with your Customers</h1>
</div>

<div class="get_connected_message">
    <h1>Build your profissional buisness world</h1>
</div>

<div class="clear"></div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

and here is the POCO that I use

public class ForCompany : DataHolder
{
    [Required]
    [StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Company Name Should  Be More Than Three Letters")]
    public string CompanyName { get; set; }

    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [Required]
    public int Country { get; set; }

    public string Description { get; set; }

    public string Logo { get; set; }

    public List<SelectListItem> Countries { get; set; }

}

but when I try to upload the file I get OutOfRange Exception, so please could anyone help me to solve this problem.

4
  • 2
    One major step you are missing is to add enctype. Like: @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post, new {enctype = "multipart/form-data" })) Commented Aug 6, 2015 at 9:53
  • possible duplicate of MVC 4 Razor File Upload Commented Aug 6, 2015 at 9:58
  • @Mehmood Ooooooh, thank you very much, how I forget something like this :o , thanks a lot, please add your comment as answer to accept it. Commented Aug 6, 2015 at 9:59
  • No no, the problem was because I did not add the enctype Commented Aug 6, 2015 at 10:04

1 Answer 1

2

You just need to add enctype = "multipart/form-data" to your begin form like so

@using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.