I am having trouble with this. I need to send a CSV file along with the value of a string variable back to the controller.
I have already managed to send the file via the submit button of the form (just through submit) and I have also managed to send the string variable back to the controller (using ajax post) but when I combine these together and its not working.
I have search for downloading/uploading files (all files types) on this forum but at this point not found what I wanted. The closest I have come to is this.
This is CSHTML form:
<form asp-action="FileIndexView"
asp-controller="SuburbsAndPostcodesAdmin"
method="post"
enctype="multipart/form-data">
<div class="form-horizontal">
<div class="form-group">
<label class="col-md-4 control-label">Select the Suburbs and Postcodes latest CSV File:</label>
<input type="file"
name="CSVFile"
id="txtFileUpload"
class="col-md-8 control-label" />
</div>
<div class="form-group">
<input type="submit"
name="Submit"
value="Submit"
class="col-md-1 btn btn-primary"
disabled="disabled"
id="SubmitFile" />
</div>
</div>
</form>
Here is the javascript:
//On button click send the connection id back to method FileIndexView.
$('#SubmitFile').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var fileUpload = document.getElementById("txtFileUpload");
var url = "/SuburbsAndPostcodesAdmin/FileIndexView";
var connId = $.connection.hub.id;
//$.post(url, {"fileUpload": file, "connId": connId });
$.ajax({
type: "POST",
url: url,
data: { file: file, "connId": connId },
processData: false,
contentType: false,
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
});
and here is the controller IActionResult:
[HttpPost]
public IActionResult FileIndexView(IFormFile file, string connId)
{
...stuff
}
Its MVC6 so I am using IFormFile.
I did try and place the contents of the id for the file into a variable but it just gets lost... You will notice I also tried using $.post as well. I can get back to the controller if I only send the string variable.
Whats wrong with the way I have tried to send the file and how should it be presented so that the controller with an IFormFile argument and string argument accept the Ajax post?