I am trying to upload a file in asp.net mvc 5 application by using the following code.

Please see the cshtml and model class and guide me what I am missing. It always return null for HttpPostedFilebase .

cshtml :

<form action="@Url.Action("send-message", "users", new { area = "security" })" class="form-horizontal" method="POST" data-async data-target="#send-message-modal" enctype="multipart/form-data">
    <div class="row">
        <div class="col-md-12">
            @Html.TextBoxFor(m => m.Email, new { placeholder = "Select the recipient...", @class = "form-control form-group-margin" })

            @Html.HiddenFor(m => m.RecipientId)
        </div>
    </div>

    @Html.TextBoxFor(m => m.Title, new { placeholder = "Enter a subject", @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Title)


    @Html.TextAreaFor(m => m.Message, new { placeholder = "Enter your message", @class = "form-control", rows = 5 })
    @Html.ValidationMessageFor(m => m.Message)

    @Html.TextBoxFor(m => m.FileNew, new { type = "file", @class = "form-control", name= "FileNew" })
    <br/>

    @Html.ValidationMessageFor(m => m.FileNew)

    <div class="panel-footer text-right no-padding-hr no-padding-b">
        <button class="btn btn-primary">Send message</button>
    </div>
</form>

ViewModel:

public class SendMessageModel
{

    [Display(Name = "Recipient")]
    [DataType(DataType.EmailAddress)]
    [StringLength(255)]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Recipient")]
    public int RecipientId { get; set; }

    [DataType(DataType.Text)]
    [Required]
    [Display(Name = "Message")]
    public string Message { get; set; }

    public bool IsSent { get; set; }

    [DataType(DataType.Text)]
    [Required]
    [Display(Name = "Subject")]
    public string Title { get; set; }

    public HttpPostedFileBase FileNew { get; set; }
}

Mvc Action :

[ActionName("send-message")]
    [HttpPost]

    public ActionResult SendMessage(SendMessageModel model)
    {

    }

1 Answers

1
Mehmet Ordu On

Add the HttpPostedFileBase parameter in method.

public ActionResult SendMessage(SendMessageModel model, HttpPostedFileBase FileNew)
{}