0

I am creating one sample form which have file upload control to upload image. The form is ajax form and the code is below;

Model:

public class MyModel
{
  [Required]
  public HttpPostedFileBase attachment { get; set; }
}

View Code:

@using (Ajax.BeginForm("UploadImage", "MyController", new AjaxOptions { HttpMethod = "POST", OnSuccess = "successSave" }, new { enctype = "multipart/form-data" }))
       {
         @Html.AntiForgeryToken()
         @Html.ValidationSummary(true)

         <div class="col-sm-10">
           @Html.TextBoxFor(model => model.attachment, null, new { type = "file" })
           @Html.ValidationMessageFor(model => model.attachment)
         </div>
         <button type="submit" class="btn btn-primary" id="btn-save">Save</button>
}

MyController.cs

    [HttpPost]
    public ActionResult UploadImage(MyModel item)
    {
        if (ModelState.IsValid)
        {
           //other save code
           if(Request.IsAjaxRequest())
           {
             return Json(result);
           }
        }
        return View(item);
    }

Through this code, if i didn't attach any image and submit, I got the Required Field validation message as we expected.

But due to ajax form, even image is attached, i didn't get the image in attachment field. AS this is expected behavior(may be my understanding), I just manipulate the submit using xhr request. So i added the following jquery script

$(function () {
window.addEventListener("submit", function (e) {
                var form = e.target;
                if (form.getAttribute("enctype") === "multipart/form-data") {
                    if (form.dataset.ajax) {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        var xhr = new XMLHttpRequest();
                        xhr.open(form.method, form.action);
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                    result = $.parseJSON(xhr.response);
                                    successSave(result);
                               }
                        };
                        xhr.send(new FormData(form));
                    }
                }
            }, true);
        });

function successSave(result) {
    if (!result || !result.resultCode) return; //If result is null not handled or Validation handled via ModelState

    if (result.resultCode == 1) {
        location.reload();
    }
    else {
        location.href = "/Error/Index?errorMessage=" + result.resultMessage;
    }
}

Now my image will successfully passed to controller.

Here for every success, i returned one json object as specified in the controller code return based on ajax request.

But in the case of validation fail (image not selected), controller returned ModelState as valid with validation message but the response is returned to the xhr.onreadystatechange function. Here it try to parse as json and script error occured and no valdiation displayed on the page.

Please help me to find the correct method and display validation errors on the page

Akhil
  • 1,918
  • 5
  • 30
  • 74
  • You cant use `Ajax.BeginForm()` to upload an image. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for one option –  Jul 07 '16 at 12:01
  • @StephenMuecke I am not asking about uploading image in ajax form. The issue is model validation not showing in page. Issue related to response / update form – Akhil Jul 07 '16 at 14:44
  • Your ajax makes no sense. Why in the world are you making an ajax call if you want to redirect. Just make a normal submit (and return the view if `ModelState` is invalid. –  Jul 08 '16 at 01:17

0 Answers0