I want to submit a form including values and an image file to server by jquery ajax and .net api controller. But the server cannot get the data, always showing a null of the input parameter.
I have added config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data")); into WebApiConfig.cs file. But it still does not work.
However, the interesting thing is that when I moved my code block into my AdminController.cs, it works.
In the following specific case, if I submit form to /admin/submitnew, it works perfectly. If submit to /api/news, newsModel on server only receive null value.
So my question is, why the data cannot be received/ready under apicontroller, and how to fix that.
NewsEdit.cshtml
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "editform" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", @id = "title" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<Lable class="control-label col-md-2">Cover Image</Lable>
<div class="col-md-10">
<input type="file" name="ImgFile" class="control-label" accept="image/png, image/jpeg" />
<br /><img src="@Model.ImgPath" style="max-width:300px" />
</div>
</div>
</div>
NewsEdit.js
$("#submit").click(function (e) {
if ($("#editform").valid()) {
e.preventDefault();
$.ajax({
url: "/admin/submitnews",
type: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
async: false,
success: function () {
****
},
error: function (e) {
****
},
})
}
AdminControllers.cs
public class AdminController : Controller{
[HttpPost]
[ValidateInput(false)]
public ActionResult SubmitNews(News newsModel)
{
//some code
}
}
NewsController.cs
public class NewsController : ApiController{
[HttpPost]
[ResponseType(typeof(News))]
public IHttpActionResult PostNewsModel(News newsModel)
{
//some code
}
}