Reputation: 17
I want to send form parameters to server.
This is my html:
<form enctype="multipart/form-data">
<div>
<label>Name: *</label>
<input type="text" id="name"/>
</div>
<div>
<label>Description: *</label>
<input type="text" id="description"/>
</div>
<div>
<label>Rules: *</label>
<input type="text" id="rules"/>
</div>
<div>
<label/>Select File to Upload: <input id="fileUpload" type="file" />
</div>
<div>
<button type="button" id="confirm" value="Confirm">Confirm</button>
</div>
</form>
Here's ajax call:
$(document).ready(function () {
$("button#confirm").click(function () {
var name = $("#name").val();
var description = $("#description").val();
var rules = $("#rules").val();
var file = document.getElementById('fileUpload');
if (file.files.length) {
var picture = file.files[0];
}
var data = new FormData();
data.append("name", name);
data.append("description", description);
data.append("rules", rules);
data.append("picture", picture);
$.ajax({
type: "POST",
async: false,
url: "/api/forum/addNewForum",
async: false,
cache: false,
contentType: undefined,
processData: false,
data: data
});
And my controller:
[HttpPost]
[AllowAnonymous]
[Route("addNewForum")]
public IHttpActionResult addNewForum()
{
var picture= HttpContext.Current.Request.Files["picture"];
return Ok;
}
But I always get null in this line
var picture= HttpContext.Current.Request.Files["picture"];
The problem is that HttpContext.Current.Request.Files.Count is always 0. This is my first time doing something like this. What am I doing wrong? And is there a better way to do this. Thanks in advance!
Upvotes: 0
Views: 1976
Reputation: 3050
Here you need to make some changes with your code.
Replace your ajax code with below.
$("button#confirm").click(function () {
var data = new FormData($("form")[0]);
$.ajax({
type: "POST",
url: "/api/forum/addNewForum",
contentType: false,
processData: false,
data: data
});
});
And then try submitting form check what response you get
Upvotes: 2