1

I'm working on an app on ASP.Net MVC 4 and am trying to upload an image in a form. The problem I'm having is that when the form posts, if the <input type="file"... is empty (meaning I have not selected a file) the form posts just fine and everything works. However, When I do select a file the form just sits there and does nothing.

At first I thought it was just taking it a while to upload but I have left it for quite some time (file size was 7kb) and nothing. the debugger doesn't even hit the breakpoints at the beginning of the action either. I'm at a loss since I'm quite new to the platform and am still learning every day. Below please find all the relevant code:

the View:

 @using (Html.BeginForm("StaffInformation", "Manager", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data"}))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true)
                <div class="control-group">
                    @Html.LabelFor(model => model.firstName, new { @class = "control-label" })
                    <div class="controls">
                        @Html.TextBoxFor(model => model.firstName, new { @class = "span12" })
                        @Html.ValidationMessageFor(model => model.firstName)
                    </div>
                </div>

                <div class="control-group">
                    @Html.LabelFor(model => model.lastName, new { @class = "control-label" })
                    <div class="controls">
                        @Html.TextBoxFor(model => model.lastName, new { @class = "span12" })
                        @Html.ValidationMessageFor(model => model.lastName)
                    </div>
                </div>

                <div class="control-group">
                    Staff Photo:
                    <div class="controls">
                        @if (Model.staffImage == null)
                        {
                            @:None
                        }else{
                        <img width="150" height="150" src="@Url.Action("GetImage", "Manager", new { Model.staffProfileID })" /><br />
                        }
                        <input type="file" id="staffImage" name="staffImage" data-provide="fileinput">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Save changes</button>
                    <a href="@Url.Action("dashboard", "manager")" class="btn" type="reset" >Cancel</a>
                </div>
            }

The Action:

    public ActionResult StaffInformation(StaffInformationViewModel model, HttpPostedFileBase staffImage)
    {
    if (ModelState.IsValid)   //This is where the breakpoint is
        {
            if (staffImage != null) {
                model.imageMimeType = staffImage.ContentType;
                model.staffImage = new byte[staffImage.ContentLength];
                staffImage.InputStream.Read(model.staffImage, 0, staffImage.ContentLength);
            }

            using (var repo = new CompanyInformationRepository(new UniteOfWorkCompanies()))
            {
                var company = repo.FindCompany(User.Identity.Name);

                repo.AddOrUpdateStaff(model, company);
            }

            return RedirectToAction("ManageStaff");
        }
    }

I really don't know whats going on and simply the reason I'm using the enctype = "multipart/form-data" is because I was reading the "Pro ASP.NET MVC 4" by Adam Freeman and in there they said that it won't work without it. Like I said, I'm quite new and need all the help I can get.

1 Answer 1

2

You can try to put the HttpPostedFileBase staffImage as part of your ViewModel (StaffInformationViewModel) - also yes, you need to keep the enctype = "multipart/form-data" in the form tag:

public class StaffInformationViewModel
{
    // your other properties here ...

    [Required]
    public HttpPostedFileBase StaffImage { get; set; }
}

Then in the View:

@Html.TextBoxFor(model => model.StaffImage, new { type = "file" })

Then in the Controller:

    public ActionResult StaffInformation(StaffInformationViewModel model)
    {
        if (ModelState.IsValid)
        {
            if (model.StaffImage != null)
            {
                // awesome
            }
            // ... more awesome
        }
    }

I hope this helps. Let me know if you need more clarifications here on this one ...

Sign up to request clarification or add additional context in comments.

8 Comments

Hi Dimitar, I can't seem to make a property of type HttpPostedFileBase inside my models project. I have tried to add a reference to the system.web.http (which I believe it lives in) but it is still not able to recognize it. My models are in a separate project as my mvc web project.
Your models can be on a separate project, but I beleive your ViewModels should not (at least that's the general convention), that's why there are ViewModels and Models. Anyway I beleive the HttpPostedFileBase is in System.Web in case you want to reference it.
ah ok, I thought they would all sit in the same place for organization but like I said, I'm quite new. I have referenced system.web, system.web.http and added a reference to the system.web.Abstractions with no luck. Do I have to include the viewmodel inside my web project for this to work?
But yes if you add the ViewModel to your MVC project you should get it Automagically :)
ok, so I had both assemblies referenced (system.web and system.web.abstractions) but I remembered that vs 2012 sometimes has a problem recognizing the added assemblies until you restart it with the project. I did that and boom its recognized. now on to trying to fix the original issue with your suggestion. be right back with the results
|

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.