I have some model classes:
public class Research
{
public int Id { get; set; }
public string Title { get; set; }
public string Abstract { get; set; }
public string Body { get; set; }
public string Image { get; set; }
[NotMapped]
public HttpPostedFileWrapper ImageFile { get; set; }
public virtual List<ResearchAuthors> ResearchAuthors { get; set; }
}
public class ResearchAuthors
{
public int Id { get; set; }
public int AuthorId { get; set; }
public int ResearchId { get; set; }
public Research Research { get; set; }
public Author Author { get; set; }
}
This is the jQuery code how I’m getting the data to be sent to the controller
var Research = {
Id: idInput.val(),
Title: titleInput.val(),
Abstract: abstractInput.val(),
ImageFile: imageInput.get(0).files[0],
Body: bodyInput.val()
};
// Research Authors
var ResearchAuthors = [];
$('#authors-tbody tr').each(function () {
var AuthorId = $(this).children('.id-td').text();
var Id = $(this).children('.researchAuthorsId-td').text();
var ResearchAuthor = {
AuthorId: AuthorId,
Id: Id,
ResearchId: idInput.val()
}
ResearchAuthors.push(ResearchAuthor)
});
The controller is waiting for this
public ActionResult Create(SaveResearchViewModel viewModel)
{
return Json(new { success = true, message = "Created Successfully" });
}
The SaveResearchViewModel
code:
public class SaveResearchViewModel
{
public Research Research { get; set; }
public List<ResearchAuthors> ResearchAuthors { get; set; }
}
I have used formdata but it won’t work because of List of ResearchAuthors
even can’t stringify because of there is image with data to be send
So what is the proper way to use with all different data types [Object, Object.Image, Arr[Object]] in order to receive in the controller?
2
Answers
form data can't add list of objects so instead you can use 2 ajax request first ajax save the Research and ReseachAuthors second ajax Save the image
like this
You can use ajax to pass 1 string to Controller. Then serializer into an object.
//Controller