Ajax FormData return null - javascript

I created a form. I am sending the data in this form as JSON.
If I just submit the formData (I also change the controller to [FromBody] Image request) and set the contentType and processData to false, the formData is not null.
I think "document" returns null because I am sending the data as JSON. How can I solve this issue I'm stuck in this issue.
Ajax Request
let myProfile = {
id: 0,
title: "",
text: "",
document: File,
};
myProfile.title = "Lorem ipsum";
myProfile.text = "Lorem ipsum";
var formData = new FormData();
formData.append('file', $('#file').get(0).files[0]);
formData.append('fileName', $("#fileName").val());
var myFile = formData.get('file');
myProfile.document = myFile;
$.ajax({
url: `/admin/myprofile`,
type: "POST",
data: JSON.stringify(myProfile),
contentType: "application/json",
dataType: 'json',
success: ....
Cshtml
<div class="form-group">
<input type="file" name="document" asp-for="document" id="file" />
</div>
Controller
[HttpPost("myprofile")]
public IActionResult MyProfile([FromBody] MyProfileDTO request)
{
return ...
}
Class
public class Image
{
public IFormFile file { get; set; }
public string fileName { get; set; }
}
public class MyProfileDTO
{
public string Title { get; set; }
public string Text { get; set; }
public Image Document{ get; set; }
}

Ajax Request
let myProfile = {
id: 0,
title: "",
text: "",
document: File,
};
myProfile.title = "Lorem ipsum";
myProfile.text = "Lorem ipsum";
var formData = new FormData();
formData.append('file', $('#file').get(0).files[0]);
formData.append('title', myProfile.title);
formData.append('text', myProfile.text);
$.ajax({
url: `/admin/myprofile`,
type: "POST",
data: formData ,
contentType: "application/json",
success: ....
Controller
[HttpPost("myprofile")]
public IActionResult MyProfile([FromBody] MyProfileDTO request, IFormFile file)
{
return ...
}
Class
public class MyProfileDTO
{
public string Title { get; set; }
public string Text { get; set; }
}

Related

How to bind JavaScript array of JSON objects to a List of objects in viewModel. dotnetcore mvc

This is my javascript array of json objects
var pObjIds = [{"Id":"2","Name":"small"},{"Id":"3","Name":"average"}]
I have collected my form fields into a FormData() like this
var form = new FormData($(this)[0]);
I have appended the array of json objects to the FormData like this
form.append("Availability", pObjIds);
I have a ViewModel with a property
public List<Item> Availability { get; set; }
The Item class looks like this
public class Item
{
[JsonProperty(PropertyName = "Id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
}
My controller method to receive the form data is
[HttpPost]
public IActionResult AddSupplier(SupplierVM vm, List<Item> list)
{
if (ModelState.IsValid)
{
}
return View("AddSupplier", vm);
}
My intention is to bind the appended Availability in the formData to the property
public List<Item> Availability { get; set; } in the ViewModel.
The above code is what I have tried but its not binding. Always returning count=0 for Availability.
Are my doing something wrong or is there a better way i can do it?
I have used FormCollection in controller but still not seen the appended array of json objects but i can log it in the console and see that it is appended successfully.
I am using dotnet core 3.0 mvc.
Thanks in advance.
This is the client side code that calls the AddSupplier
var form = new FormData($(this)[0]);
form.append("Availability", pObjIds);
$.ajax({
type: 'POST',
url: '/supplier/addsupplier/',
data: form,
processData: false,
contentType: false,
datatype: 'json',
success: function (result) {
if (result.status == false) {
swal({
title: 'Error!',
text: result.msg,
icon: "error",
button: "Ok",
});
}
},
error: function () {
swal({
title: "Unknown Error!",
text: "unable to process request!",
icon: "error",
button: "Ok",
});
}
});
I have a ViewModel with a property
public List<Item> Availability { get; set; }
My intention is to bind the appended Availability in the formData to the property public List<Item> Availability { get; set; } in the ViewModel.
To achieve your requirement, you can try to append values for FormData object like below.
var form = new FormData($(this)[0]);
//form.append("Availability", pObjIds);
$(pObjIds).each(function (index, el) {
form.append(`Availability[${index}].Id`, el.Id);
form.append(`Availability[${index}].Name`, el.Name);
});
$.ajax({
type: 'POST',
url: '/supplier/addsupplier/',
data: form,
processData: false,
contentType: false,
datatype: 'json',
success: function (result) {
// code logic here
//...
In controller action AddSupplier
[HttpPost]
public IActionResult AddSupplier(SupplierVM vm)
{
//code logic here
View model class SupplierVM
public class SupplierVM
{
public int Id { get; set; }
//other properties
public List<Item> Availability { get; set; }
}
Test Result

Passing an object with values from View to ActionResult using ajax

I want to send an object from view to controller, ajax hits the action result but data is not being delivered to action result
View:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: '{obj' + JSON.stringify(obj) + '}',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
Model:
public class QAViewModel
{
public string C { get; set; }
public string EE { get; set; }
public string MD { get; set; }
public string ME { get; set; }
public string PD { get; set; }
public string RT { get; set; }
public string SEA { get; set; }
public string SED { get; set; }
}
Controller:
Editing as a good point was raised:
In the post you can just pass the full object like so:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: obj,
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
If you want to stick with json then modify your ajax call accordingly (you error was in the way you were building the data property:
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: JSON.stringify({obj: obj}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
Also, depending on what you are doing with the result you may need to flip your controller actions to return JsonResult (Ignore if you are doing something such as returning a partial view to load):
[HttpPost]
public JsonResult Whatever(QAViewModel obj)
{
return Json(whatever, JsonRequestBehavior.AllowGet);
}

How to pass a object with list object from javascript to controller in .Net

I am currently trying to send an object with a list, but I do not understand why sends the object but the list I receive zero.
Structure:
public class Provider
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Articles> Articles { get; set; }
}
public class Articles
{
public int Id { get; set; }
public string Name { get; set; }
}
Javascript
var articles = [];
articles.push({ Id: 1, Name: "Article Name 1" });
articles.push({ Id: 2, Name: "Article Name 2" });
var provider = {
Id: 1,
Name : "Provider Name",
Articles : articles
};
And i used this call ajax
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/Provider/Save",
type: 'post',
dataType: 'json',
data: JSON.stringify({ provider: provider}),
cache: false,
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
Controller
[HttpPost]
public ActionResult Save(Provider provider)
{
// Code here
return View();
}

HttpPostedfileBase is null using jQuery Ajax

I have problem with uploading file In Asp.net Mvc. First of all I should use Ajax to pass the upload file value.
In javascript I have model that I fill it, When I check it with debugger is correctly fill the object, but when I send this model to server (Controller )
The httpPostedfileBase value is Always null.
I search it on google, in some post I saw that I cant use file uploader with Ajax, but in other I saw that I can.
But I can not fix my Code.
There is my Javascript Code.
$(document).ready(function () {
$('#btnUploadFile').on('click', function () {
var data= new FormData();
debugger;
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
data.append("UploadedImage", files[0]);
}
var ResturantSharingViewModel =
{
Type: $("#SharingTargetType").val(),
SharingTitle: $("#SharingTitle").val(),
content: $("#Content").val(),
ItemId : $("#ItemId").val(),
Photos: files[0]
};
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '<%= Url.Action("SaveOneDatabase")%>',
data: JSON.stringify(ResturantSharingViewModel),
success: function (result) {
var rs = result;
},
error: function () {
alert("Error loading data! Please try again.");
}
});
My Controller public virtual bool SaveOneDatabase(ResturantSharingViewModel result)
My ResturantSharingViewModel View Model
public class ResturantSharingViewModel
{
public Guid SharingPremiumHistoryID { get; set; }
public string SharingTitle { get; set; }
public string Content { get; set; }
public DateTime AddedDate { get; set; }
public bool IsSubmit { get; set; }
public DateTime SubmitedDate { get; set; }
public IEnumerable<SelectListItem> SharingTypes { get; set; }
public IEnumerable<SelectListItem> SharingTargetType { get; set; }
public short Type { get; set; }
public Guid ItemId { get; set; }
public HttpPostedFileBase[] Photos { get; set; }
}
My Html Elements
<form enctype="multipart/form-data">
<article>
<%--<% =Html.BeginForm("Add","PremiumSharing") %>--%>
<hgroup class="radiogroup">
<h1>ارسال خبر</h1>
<%= Html.HiddenFor(model => model.SharingPremiumHistoryID) %>
<%= Html.HiddenFor(model => model.ItemId) %>
<div class="group">
<span> ارسال به </span>
<%= Html.DropDownListFor(model => model.SharingTargetType, Model.SharingTypes) %>
</div>
</hgroup>
<div class="newseditor">
<div class="input-form">
<%= Html.LabelFor(model => model.SharingTitle, "عنوان خبر") %>
<%= Html.TextBoxFor(model => model.SharingTitle) %>
</div>
<div class="input-form">
<%= Html.LabelFor(model => model.Content, "متن خبر") %>
<%= Html.TextAreaFor(model => model.Content) %>
</div>
<div><input id="fileUpload" type="file" />
</div>
<% if (ViewBag.IsInEditMode != null && !(bool)ViewBag.IsInEditMode)
{%>
<div class="input-form">
<%= Html.CheckBox("SendToInTheCity") %> ارسال در بخش «در شهر» فیدیلیو
</div>
<%} %>
<div class="input-submit">
<button name="post" id="btnUploadFile" onclick="uploadFile()" >ارسال خبر</button>
</div>
<br />
</div>
First, it's possible to upload with Ajax, the important thing is you need to set <form enctype="multipart/form-data"></form> on you form to tell it your form has an file upload input. Then you need to accept HttpPostedFileBase as an input parameter in your controller action.
Try this. Example of jquery upload code. (Taken mostly from How can I upload files asynchronously?)
function uploadFile(uploadId) {
var formData = new FormData($('form')[0]);
$.ajax({
url: '<%= Url.Action("SaveOneDatabase")%>',
type: 'Post',
beforeSend: function(){},
success: function(result){
},
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload) { // Check if upload property exists
// Progress code if you want
}
return myXhr;
},
error: function(){},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
HTML Form needs this attribute. See this post why you need it -> What does enctype='multipart/form-data' mean?
enctype="multipart/form-data"
C#
[HttpPost]
public ActionResult SaveOneDatabase(HttpPostedFileBase file)
{
}
I have modified #a moradi's answer.
JS:
//FormData:
//Consider it a normal form but with "multipart/form-data" encoding type.
//Inside it works same as XMLHttpRequest.send() method.
var model = new FormData();
model.append("File", $('#file')[0].files[0]);
model.append("Name", "Name");
$.ajax({
url: someUrl,
type: "POST",
data: model,
//contentType:
//Sets the ContentType in header.
//The default contentType is "application/x-www-form-urlencoded; charset=UTF-8". But this will prevent us sending AntiForgeryToken to service/controller.
//To prevent this contentType is set to false.
contentType: false,
//processData:
//To prevent data getting converted to string format, 'processData' option is set to false.
processData: false,
success = function (m) {...}
error = function (m) {...}
});
View Model:
public class PhotoAlbumViewModel {
public string Name { get; set; }
public HttpPostedFileBase File { get; set; }
}
Controller:
public JsonResult AddPhoto(PhotoAlbumViewModel model) {
...
}
Refrence:
Reffer following links for details: FormData , JQuery , ContentType
View:
<script/>
var add_photo_url = "#Url.Action("AddPhoto", "Gallery")";
var model = new FormData();
var i=0;//selected file index
model.append("File", files[i]);
model.append("Name", "test");
$.ajax({// and other parameter is set here
url: add_photo_url,
type: "POST",
data: model,
dataType: "json",
cache: false,
contentType: false,
processData: false
})
.always(function (result) {
});
</script>
View Model:
public class PhotoAlbumViewModel {
public string Name { get; set; }
public HttpPostedFileBase File { get; set; }
}
Controller:
public JsonResult AddPhoto(PhotoAlbumViewModel model) {
// var result =...
// and set your result;
return Json(result, JsonRequestBehavior.AllowGet);
}

Format JSon so that mvc4 controller method can parse it

My controller Action:
[HttpPost]
public ActionResult H80Count(IEnumerable<H80SearchCriteria> model)
{
do some stuff and return Json;
}
My model:
public class H80SearchCriteria
{
public int ID { get; set; }
public int Operator { get; set; }
public string FieldID { get; set; }
public string Kriterie { get; set; }
}
My Javascript:
var SearchCriteria = [];
var i = 0;
$('#tableSearchValues > tbody').find('tr').each(function () {
i += 1;
var row = {
ID : i,
Operator : $(this).data('operator'),
FieldID : $(this).data('fieldid'),
Kriterie: $(this).data('kriterie')
};
SearchCriteria.push(row);
});
var url = '/MyController/H80Count';
var data = JSON.stringify(SearchCriteria) ;
$.ajax({
type: 'POST',
url: url,
data: data,
etc...
The Json that is passed looks like this:
[{"ID":1,"Operator":1,"FieldID":1,"Kriterie":11211},{"ID":2,"Operator":1,"FieldID":1,"Kriterie":11211}]
I can't see why it is not parsed correctly. What am I missing?
I think you forgot the contentType: 'application/json' on ajax function.
It works for me.
try this instead of IEnumerable use array and place [FromUri] or [FromBody] which looks for values in the Uri or Body of the request.
[HttpPost]
public ActionResult H80Count([FromUri] H80SearchCriteria[] model)
{
do some stuff and return Json;
}
and dont forget to set the traditional ajax settings as true
$.ajax({
type: 'POST',
url: url,
data: data,
traditional: true
});

Categories

Resources