Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create MVC 4 @Html.TextBox type="file"?

I need to add the following field at my form

<input type="file" class="input-file" />

I create model and describe this field (the last field)

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

 namespace CorePartners_Site2.Models
 {
     public class FeedbackForm
     {
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    public string AdditionalInformation { get; set; }
    public HttpPostedFileBase ProjectInformation { get; set; }
     }
 }

and create

@Html.TextBox(null, null, new { type="file", @class="input-file" })

but it doesnt work, I get some exception. What's wrong?

like image 929
Heidel Avatar asked May 20 '13 07:05

Heidel


1 Answers

Model

public class FeedbackForm
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    public string AdditionalInformation { get; set; }
    public HttpPostedFileBase ProjectInformation { get; set; }
}

View

@model FeedbackForm

@Html.TextBox("Name")
@Html.TextBox("Email")
...
@Html.TextBox("ProjectInformation", null, new { type="file", @class="input-file" })

// submit button

My recommended view (strongly - typed)

@model FeedbackForm

@Html.TextBoxFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Email)
...
@Html.TextBoxFor(model=>model.ProjectInformation, null, new { type="file", @class="input-file" })

// submit button

Controller

[HttpPost]
public ActionResult FeedbackForm(FeedbackForm model)
{
    // this is your uploaded file
    var file = model.ProjectInformation;
    ...

    return View();
}

MVC is using name convention, so if your textbox and model names match, then MVC will bind your inputs to your model.

like image 104
AliRıza Adıyahşi Avatar answered Oct 27 '22 04:10

AliRıza Adıyahşi