I have complex form with strings, files. And I'm adding to this form some JSON/object.In controller I can't handle my added object(Product) you can see it below.
Models
Model 1. MyData
public string SomeThing { get; set; }
public IEnumerable<Product> Products { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
Model 2. Product
public int Id { get; set; }
public int Count { get; set; }
Controller
[System.Web.Http.HttpPost]
public HttpStatusCodeResult GetData(MyData data) <== SomeThing-OK.Files-OK,Products-Products[0]
{
//logic
}
JS. I'm using Vue fetch API but it isn't a deal.The same thinks occurrence when I use JQuery.
let form = new FormData(this.$refs.myForm);
form.append('Products', [{ 'Id': 1, 'Count': 2 }]) <== In controller I always get Products[0] =(
fetch('/GetData', {
method: 'post',
body: form
})
})
I'm totally confused. I don't want refuse using FormData(). I can easily handle files with it. But my controller doesn't see any complex(Products) object if I don't use JSON(stringify). I will be grateful for any advice.
Related
On frontend (appending image file, and JavaScript object with details about product):
let f = new FormData();
f.append('File', file);
objectToSend = {
...values
};
f.append('ProductDto', objectToSend );
await createProduct(f);
export const createProduct = async data => {
return axiosWrapper.request({
url: `/products`,
method: 'POST',
data: data,
});
};
On backend (receiving appended data as FromForm):
// POST: api/products
[HttpPost]
public async Task<IActionResult> Post([FromForm]ProductFile file)
{
// Create product
}
ProductFile class looks like this:
public class ProductFile
{
public IFormFile File { get; set; }
public ProductDTO ProductDto{ get; set; }
}
Issue is that ProductDto is always null, while File is populated as it should be.. I don't understand why is that ?
P.S I've tried appending it like this also:
f.append('ProductDto', JSON.stringify(objectToSend));
Cheers
You are appending an object in FormData. Form data accepts key-value pairs where the value is expected to be a string as described here.
Try converting the object to a string first
f.append('ProductDto', JSON.stringify(objectToSend) );
Then in your backend, before accessing it, convert it back to an object.
Your problem is that the content-type of the request is formdata so ASPNET uses a FormData Model Binder to populate the properties of the model. This model binder won't be able to deserialize the json and bind it to the model.
If you want the model binder to be able to set the values of the properties of you object they need to be defined as formdata in your request.
For exemple if your object as a structure like this :
public class ProductDTO
{
public int ProductId { get; set; }
public string Name{ get; set; }
}
You'll need to do :
f.append('ProductDto.ProductId', objectToSend.productId );
f.append('ProductDto.Name', objectToSend.name);
Another solution is to use a string in your model, and deserialize the DTO yourself :
public class ProductFile
{
public IFormFile File { get; set; }
public string ProductDto { get; set; }
}
[HttpPost]
public async Task<IActionResult> Post([FromForm]ProductFile file)
{
var productDto = JsonConvert.DeserializeObject<ProductDTO>(file.ProductDto);
}
So I have been learning some .net core and I am building an API with it. Normally I would work with angular and send requests there.
I have the following angular snippet:
//The data I need to send.
$scope.PersonalInfo = {
firstName: '',
lastName: '',
companyName: '',
email: '',
password: '',
confirmPassword: '',
imageLink: ''
};
Then there's the backend model for the same data:
public class UserProfileModel
{
public string userID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string companyName { get; set; }
public string email { get; set; }
public string password { get; set; }
public string confirmPassword { get; set; }
public string imageLink { get; set; }
}
And finally the method that should send it:
$scope.UpdateProfile = function () {
var profile = JSON.stringify($scope.PersonalInfo);
$http.post('/api/Profile/Users', profile).then(function (response) {
debugger;
$log.log(profile);
$log.log(response);
});
};
No matter how many changes I have done, (send the data as a stringified JSON, or send the scoped object), when the request hits the controller, I end up with this:
$scope.PersonalInfo is full of data before the request is sent.
Any help is very appreciated. Thanks in advance.
You need to mention [FromBody] attribute in your post call. Like So,
[HttpPost]
[Route("api/bar/users")]
public IActionResult Users([FromBody]UserProfileViewModel profile)
{
return Json(new { Data = profile });
}
That should do it.
The necessity to use the FromBody attribute is so that the framework can use the correct input formatter to model bind. The default formatter used, for example, with content type application/json is the JSON formatter based on Json.Net
Detailed information at: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
I'm posting some form data through ajax to my server. I also grab a some Id's from an array in memory and add it to the form data:
var postData = $('#frmMoveToNewPackage').serializeArray();
postData.push({
name: 'DocumentIds',
value: _checkboxList.getAllChecked()
});
$.post('#Url.Action("MoveToNewPackage")', postData);
My model is this:
public class MoveToNewPackageModel
{
[Required]
public int OldPackageID { get; set; }
[Required]
public Package NewPackage { get; set; }
public List<string> DocumentIds { get; set; }
}
This works. However technically the list of DocumentIds should be a List<int>. If I change the type in my modal, and change the post data:
postData.push({
name: 'DocumentIds',
value: _checkboxList.getAllChecked().map(function(item) { return parseInt(item);});
});
Then my DocumentIds is an empty (but not null) list of ints. I've looked at the data being posted and it's a valid int array.
EDIT: Above is wrong. It was not correctly binding the list of strings. It was just jamming everything into the first item of the string array.
I'm working on a web-api controller. I built a DTO to hold a Note.
public class NoteContainer
{
public long? NoteId { get; set; }
public string Type { get; set; }
public string NoteText { get; set; }
public NoteContainer(Note note, string type = null)
{
NoteId = note.Id;
NoteText = note.NoteText;
Type = type;
}
}
I have a method in my controller:
[HttpPost]
public void EditNote(NoteContainer container)
{
//do work here
}
Before the NoteContainer is sent from the client it has all values. When it gets to the server, type is null! Should I not use a variable named type? Why am I losing the value?
Using Postman I'm sending this json:
{
"noteId": 10,
"type": "person",
"noteText": "loves broccoli",
}
That needs default constructor I believe. The problem can be that the Note class gets instantiated first and is given to NoteContainer.
I have a game object in client side JavaScript that looks like this right before being sent to the server:
Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.
Here is the code for the models:
public class Game
{
public Game()
{
Questions = new List<Question>(5);
}
public int GameID { get; set; }
public Guid UserID { get; set; }
public Guid CurrentGameID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public IEnumerable<int> Answers { get; set; }
public int SelectedAnswer { get; set; }
}
And here is how I send the object back to the server:
// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
// display results to user
}
Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:
$.ajax(
{
url: "Games/CompleteGame",
type: "POST",
data: JSON.stringify(currentGame),
contentType: "application/json",
success: function (results)
{
// show results to user...
}
As it turns out, this was all it needed to make it work.