0

I am working on an ASP.NET MVC 4 application and there are many views where the user can upload a file which I save on the server using Ajax.

My View page is,

 <div class="row">
              <br />
             <div class="col-md-4" >
                @Html.TextBoxFor(m => m.fileUpload, new { @class = "form-control", style = "height:33px;", type = "file", accept = "image/*,application/pdf" }).DisableIf(() => Model.IsReadOnly == true)
            </div>

            @if (Model.Status != Intranet.Common.Constants.Status.View)
            {

                <div class="form-group">
                    <button id="btnSubmitUpload" name="Command" value="Save"    
                        class="btn btn-default">
                       Upload
                    </button>
                </div>
            }
 </div>


<script type="text/javascript">
   var model = @Html.Raw(Json.Encode(Model))
   $(document).ready(function () {
          $("#btnSubmitUpload").click(function (event) {

            $("#divLoading").hide();
            event.preventDefault();
         getTempUpload(event);

          });
    });

  function getTempUpload(event)
  {
       var formData = new FormData($('fileUpload')[0]);
        $.ajax
            ({
                type: 'POST',
                async: false,
                url: RootUrl + "DocumentUpload/fnUpload",
                data: { fileNamearg: formData  },
                cache: false,
                datatype: "Json",
                success: function (data) {
                    if (data != "") {
                         alert(data);
                    }
                },
                error: function (error) {
                    alert('Error' + error.responseText);
                }
            });
     }
 </script>

In My model,

    [FileTypes("pdf,jpg,jpeg,gif,tif,tiff,png")]
    [DisplayName("File Upload")]
    public virtual HttpPostedFileBase fileUpload { get; set; }

    public string DocExtesnsion { get; set; }

    public string DocPath { get; set; }
    ...                                 
    ...  

And Ajax method is,

     public JsonResult fnUpload(HttpPostedFileBase fileNamearg, FormCollection frmcoll)
    {

        TrnMstDocUploadModel model=new TrnMstDocUploadModel();

        String resultMsg = string.Empty;
        model.fileUpload = fileNamearg;  
        if (model.FileNameArg != null)
        {

                  if (Convert.ToString(ConfigurationManager.AppSettings["UploadFileSizeValidation"]).ToUpper() == "YES")
                  {
                      if ((fileNamearg.ContentLength / 1024) / 1024 > Convert.ToInt32(ConfigurationManager.AppSettings["UploadFileSize"].ToString()))
                      {
                                resultMsg = "Maximum File Size Exceeded " + ConfigurationManager.AppSettings["UploadFileSize"].ToString() + " MB.";
                      } 


                      if (string.IsNullOrEmpty(resultMsg))
                      { 
                        TempSave("", model, out resultMsg);
                        return Json(resultMsg,JsonRequestBehavior.AllowGet);           

                      } 
                }
        }
        return Json("", JsonRequestBehavior.AllowGet);
    }

The fnUpload method is working fine, but Here the problem is fileNamearg parameter is null. It is working when I tried it using form action and HttpPost methods. But I want to do it with Ajax. So how to pass the HttpPostedFileBase parameter to Ajax Method?. Please anybody help

Md Aslam
  • 1,228
  • 8
  • 27
  • 61
  • Using `data: formData,` and changing the parameter in your method to `HttpPostedFileBase fileUpload` should work (but I assume `FormData($('fileUpload')[0]);` is a typo? - it should be `$('#fileUpload')`) –  Feb 04 '16 at 04:46
  • But some of the code in your method makes no sense. Why do you have `FormCollection frmcoll` parameter? Why are you using `model.fileUpload = fileNamearg;`? –  Feb 04 '16 at 04:50
  • I tried what you said, but it shows the error "JavaScript runtime error: Argument not optional" – Md Aslam Feb 04 '16 at 04:53
  • Because The "model.fileupload" object/variable is used in the TempSave method – Md Aslam Feb 04 '16 at 04:55
  • I see now that you have not set the `processData:` and `contentType:` options :) –  Feb 04 '16 at 04:57
  • @Stephen, But Still now the null value is passing to the fileUpload paramater. Please can you help me with some code – Md Aslam Feb 04 '16 at 05:04
  • The answer I linked to shows the correct code. Wrap the input(s) in a `
    ` tag and change the parameter in your POST method to `HttpPostedFileBase fileUpload` - it will all be bound correctly
    –  Feb 04 '16 at 05:08
  • Yeah, I tried it. But still null value passing – Md Aslam Feb 04 '16 at 05:18
  • Then you have not used the code in the linked answer and/or not made the changes in my comments above (or you using an old browser which does not support `FormData`) –  Feb 04 '16 at 05:26

0 Answers0