skip to Main Content

I get model’s values from view with this codeblock and this part is OK.

var data = new FormData();

var datas = $(this).serializeArray();
for (var i = 0; i < datas.length; i++) {
    data.append(datas[i].name, datas[i].value);
}

In addition I want to add a list to data variable with this code block.

commentlist.push({ CommentID: commentguid, UserName: username, Comment: comment, MainCommentID: topcommentid });
data.append("Comments", commentlist);

And this is the list in my model from controller side.

public List<CommentModalClass> Comments { get; set; }

In summary I want to send commentlist to controllerside in data but I couldn’t make it.

2

Answers


  1. For passing the array of objects in FormData, the properties should be as below:

    Comments[<index>].<Property name>
    

    Thus it should be looked like:

    Comments[0].CommentID: <commentguid>
    Comments[0].UserName: <username>
    Comments[0].Comment: <comment>
    Comments[0].MainCommentID: <topcommentid>
    
    for (let i = 0; i < commentlist.length; i++) {
      let comment = commentlist[i];
      for (let prop in comment) {
        data.append(`Comments[${i}].${prop}`, comment[prop]);
      }
    }
    
    Login or Signup to reply.
  2. Serialize the comments data in Jquery and send using Ajax call. For server side function definition should received a string and within that action method deserialize the data into your view model comments property i.e.

    In JavaSript file:

    $(document).ready(function ()
    {
        var comments = JSON.stringify(data)
    
        $.ajax(
        {
            type: 'POST',
            dataType: 'JSON',
            url: '/MyController/GetCommentsData',
            data: { lstComments: comments },
            success:
                function (response)
                {
                   // Success
                   return response; 
                }
        });
    });
    

    In Your Code file:

    ...
    
    Using Newtonsoft.Json
    
    ...
    
    public bool GetCommentsData(string lstComments = "")
    {
       // Initialization.
       bool isValid = true;
       MyModel model = new MyModel();
    
       // Verification
       if (string.IsNullOrEmpty(lstComments))
       {
          // Fail.
          isValid = false;
          return = isValid;
       }
    
       // Deserialize Input JSON String into target Object Mapper.
       MyModel.Comments = JsonConvert.DeserializeObject<List<CommentModalClass>>(lstComments);
    
    ...
       
       // Process your Data.
    
    ...
    
       // Success.
       return isValid;
    }
    
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search