简体   繁体   中英

FormData Values in Razor HTML page, getting in C# Method

I have following input element in razor view page

<input type="file" id="uploadFile" name="FileUpload" multiple="multiple" />

using following script I'm binding data to this ForData

$('#uploadFile').on('change', function()
{

  var fd = new FormData();
  var files = $('#uploadFile')[0].files;


  for (var i = 0; i < files.length; i++) 
  {
    if (files[i].size < 5242880) 
    {       
       fd.append("myFiles", files[i])
    }
  }  
});

I'm trying to get these files in C# method like following

[HttpPost]        
public ActionResult SomeAction(ModelClass model)
{
    var attchaedfiles = System.Web.HttpContext.Current.Request.Files["myFiles"];

                for (int i = 0; i < attchaedfiles.Count; i++)
                {
                    if (!string.IsNullOrEmpty(attchaedfiles[i].FileName))
                    {
                      ....
                    }
                }
}

but here I'm getting folllowing errors

Operator '<' cannot be applied to operands of type 'int' and 'method group'

Cannot apply indexing with [] to an expression of type 'System.Web.HttpPostedFile'

In your ajax script, make sure you include these:

$.ajax({
    url: yourUrl,
    type: 'POST',
    // Needed for FormData submit
    processData: false,
    // Needed for FormData submit
    contentType: false,
    data: fd,
    dataType: 'json',
    success: function () {
        // Success things
    },
    error: function () {
        // Error things
    },
    complete: function () {
        // Complete things
    }
});

And that your form code includes enctype = "multipart/form-data":

@using (Html.BeginForm(null, null, FormMethod.Post, new { @action = YourAction, id = "your_id", enctype = "multipart/form-data" }))

Try the following approach that checks possible conditions regarding to file uploads:

Model:

public class ExperimentViewModel
{
    public int Id { get; set; }

    [DataType(DataType.Upload)]
    public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }

    //other properties
}


Controller:

if (model.FileUpload != null)
{
    if (model.FileUpload.Count() > 0)
    {
        foreach (var upload in model.FileUpload)
        {
            if (upload != null && upload.ContentLength > 0)
            {
                //your stuff
            }
        }
    }
}

You can also look at my answer on How to display images in MVC .

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM