0

I have a serialised object

{
a: “test”,
B[1].Name : “test”,
B[1].Surname : “testing”,
Etc.

But when I sent this object in using ajax Post method in cshtml file, my model is setting the list of b to null

When I’m actual fact I am sending data, but not in the correct format for the controller to understand

How do I serialise the object even further to send the correct model to the controller like

{
a: “test”,
B: {{ Name : “test”,Surname : “testing”}}
Etc.
3
  • 2
    What is B ? From your first example, it looks like a List of objects? which would be something like B: [{"Name": "test", "Surname": "testing"}]. But what do you mean by "how do I serialize"? You don't do it manually, do you? Commented Jan 17, 2024 at 11:55
  • 1
    But when I sent this object in using ajax Post method in cshtml file, my model is setting the list of b to null -- then please edit your question to share a minimal reproducible example as suggested in How to Ask: Help others reproduce the problem... if your problem is with code you've written, you should include some. But don't just copy in your entire program... Include just enough code to allow others to reproduce the problem. Thanks! Commented Jan 17, 2024 at 14:58
  • 1
    Also, please let us know what library and .NET / .NET Core versions you are using. You tagged the question asp.net-ajax but this particular library is very old (introduced in 2007). Commented Jan 17, 2024 at 15:07

1 Answer 1

1

You typically serialize json by using a serialization library, for example System.Text.Json.

To serialize a list, just create a list or array of your objects, and give it to the library for serialization

public record MyClass(int Age, string  Name)
...
var list = new List<MyClass>(){new (50, "Bilbo"), new (2931 , "Legolas") };
var json = JsonSerializer.Serialize(list);

Resulting in:

[
{"Age":50,"Name":"Bilbo"},
{"Age":2931 ,"Name":"Legolas"}
]

I.e. an Json array of objects.

I'm not sure what your example is supposed to be, or how you created it, but it does not look like json.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.