Question

I am trying to add an image by using MVC 4 ajax form, but it always returns null value. I added my model, controller and view.

My View

    @using (Ajax.BeginForm("Create", "Images", new AjaxOptions { HttpMethod = "Post", OnSuccess = "OnSuccess", OnFailure = "OnFailure", UpdateTargetId = "messageDiv" }, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div class="editor-field">
                    @Html.LabelFor(model => model.Image.Description, new { @class = "control-label" })
                    <div class="controls">
                        @Html.TextBoxFor(model => model.Image.Description)
                    </div>
                    @Html.TextBoxFor(model => model.FileImage, new { type = "file" })
                   @Html.ValidationMessageFor(model => model.FileImage)
                </div>...
    }

My Model

public class ImageViewModel
    {

        public IList<Image> Images { get; set; }
        public Image Image { get; set; }
        public HttpPostedFileBase FileImage { get; set; }

    }

My Controller

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ImageViewModel model, HttpPostedFileBase FileImage)
        {
            if (ModelState.IsValid)
            {
                var x = FileImage.FileName;
                var imageUrl = Path.GetFileName(model.FileImage.FileName);
                ...
            }
        }

In this example, I could not get the FileName. it returns always null value. Could you help me to solve this problem. I will be very happy.

Was it helpful?

Solution

I would prefer read the image using the request intead of trying to bind that to a model,

public ActionResult Create(ImageViewModel model)
{
    if (Request.Files != null)
    {
        HttpPostedFileBase file = Request.Files[0]; //assuming that's going to be the first file 
        if (file.ContentLength > 0)
        {
           string fileName = Path.GetFileName(file.FileName);
           string directory = Server.MapPath("/"); //change ths to your actual upload folder
           file.SaveAs(Path.Combine(directory, fileName));
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top