vaibhav shah
vaibhav shah

Reputation: 5069

Pass image & data from view to controller

I want to pass image as well as some data from view to controller on submit button click. Bellow is my code

My View

@using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data", accountId = Model.accountId }))
{
       <text>Post Photo : </text> <input type="file" name="file" id="file" />

       <input type="submit" value="Post Photo" id="saveButton"/>
}

My controller action

 [HttpPost]
 public ActionResult AccountPhotoPost(HttpPostedFileBase file, long accountId)
    {

    }

Here problem is that as it is FormMethod.Post , data is not passed from view to controller & if I remove this then data is passed but image is not passed.

How can I send both together ?

Upvotes: 1

Views: 6847

Answers (2)

Saranya Devi
Saranya Devi

Reputation: 51

Try This

 HttpPostedFileBase hpf = Request.Files["file"] as HttpPostedFileBase;
                var httpPostedFileBase = Request.Files["file"];
                if (httpPostedFileBase != null && (hpf != null && httpPostedFileBase.ContentLength > 0))  
                {
                    var postedFileBase = Request.Files["file"];
                    if (postedFileBase != null)
                    {
                        fileName = postedFileBase.FileName;
                        BinaryReader reader = new BinaryReader(postedFileBase.InputStream);
                        byte[] attachmentBinary = reader.ReadBytes((int)postedFileBase.ContentLength);
                        hcUserReview.AttachmentByteValue = attachmentBinary;
                        hcUserReview.FileName = fileName;
                    }
                }

Upvotes: 1

Shivkumar
Shivkumar

Reputation: 1903

Try this

@model SomeModel
@using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
       <text>Post Photo : </text> <input type="file" name="file" id="file" />

        @Html.HiddenFor(model => model.accountId )
       <input type="submit" value="Post Photo" id="saveButton"/>
}

in Controller

[HttpPost]
 public ActionResult AccountPhotoPost(SomeModel model ,HttpPostedFileBase file)
    {
        var Id = model.accountId;
    }

Upvotes: 1

Related Questions