Home > Back-end >  How to send List of objects and image from jquery to mvc controller
How to send List of objects and image from jquery to mvc controller

Time:11-16

I got a model Research

 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; }
 }

and ResearchAuthors Model

 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; }
 }

and this is the jqeury 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 Stringfy because of there is image with data to be send

so what is the prober way to use with all different dataTypes [Object, Object.Image, Arr[Object]] in order to Receive in the controller

CodePudding user response:

You can use ajax to pass 1 string to Controller. Then serializer into an object.

var Research = {
Id: idInput.val(),
Title: titleInput.val(),
Abstract: abstractInput.val(),
ImageFile: imageInput.get(0).files[0],
Body: bodyInput.val()};

$.ajax({
url:'/Controller/Action',
data: {
    strResearch: JSON.stringify(Research)
},
type: 'POST',
dataType: 'json',
success: function(res){
    if(res.success)
    {
        alert(res.message)
    }
}

//Controller

    public JsonResult Create(string strResearch)
    {
        SaveResearchViewModel saveResearchViewModel = new SaveResearchViewModel();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Research objResearch = serializer.Deserialize<Research>(strResearch);
        //save db

        return Json(new { success = true, message = "Created Successfully" });
    }

CodePudding user response:

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

 $.ajax({
                type: "POST",
                dataType: "json",
                url: "/Researches/Create",
                data: viewModel,
                success: function (data) {
                    if (data.success) {
                        $.ajax({
                            url: "/Researches/SaveImage",
                            method: "POST",
                            processData: false,
                            contentType: false,
                            data: data,
                            success: function (data) {
                                if (data.success) {
                                    toastr.success(data.message);
                                    window.location.replace("/Researches/");
                                }
                            },
                            error: function () {
                                toastr.error("Image Ajax error");
                            }
                        })   
                    }
                    else {
                        toastr.error(data.message)
                    }
                },
                error: function () {
                    toastr.error("Ajax Error")
                }
  • Related