0

I am currently developing uploading image using ASP.NET MVC 5. I got the some problem with uploading image together with view model. Uploading image only is working well as the following. here is my controller.

[HttpPost("fileUpload")]
public async Task<JsonResult> fileUpload(IFormFile file)
{            
    try
    {
        //MY JOB IS HERE
    }catch(Exception ex){
        //SOME EXCEPTION WILL BE HERE
    }
}

Here is javascript:

var files = new FormData();
files.append('file', updfile.files[0]);      

$.ajax({
    url: url,
    data:files,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data.responseText);
        displayLoading(false);
    },
    error: function (err) {
        alert(err.responseText);
        document.getElementById("image").src = "#";
        displayLoading(false);
    }
});

and HTML :

<div class="col-md-6">
    <form id="frmABC" method="post" enctype="multipart/form-data">
        <div id="loading" name="loading">LOADING</div>
        <input type="file" id="files" name="files" onchange="file_OnChange('@ServerLink.configCollection["FileUploadApiLink"]',this,'@Model.SysKey')" />                                
         <div style="width:200px;height:200px;border:1px solid #70c3ff">                                  
            <img id="image" style="max-height:100%;max-width:100%;background-color:red" src="@ServerLink.configCollection["GetCompanyPictureByID"]/@Model.SysKey" />
        </div>
    </form>                       
</div>

So my problem is that i want to add another veiw model beside of IFormFile parameter in controller. Such as

public async Task<JsonResult> fileUpload(IFormFile file, myInfVM infovm)

and my myInfVM :

public class myInfVM
{                        
    public string CompanySK { get; set; }
    public string CompanyName { get; set; }
}

I tried the following method but no luck.

var files = new FormData();
files.append('file', updfile.files[0]);      

$.ajax({
    url: url,
    data:{ file : files, infovm : { CompanySK : '123', CompanyName : 'ABC' } },
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data.responseText);
        displayLoading(false);
    },
    error: function (err) {
        alert(err.responseText);
        document.getElementById("image").src = "#";
        displayLoading(false);
    }
});
DavidG
  • 113,891
  • 12
  • 217
  • 223
Dartfrog Imi
  • 489
  • 2
  • 11
  • 26

0 Answers0