MeeraWeeks
MeeraWeeks

Reputation: 93

JSON object to ASP.NET MVC

I know there are multiple threads around this issue, but I still can't figure mine out. Can someone please help me figure out why my classObject always has null value? I feel like I've tried everything by now.

My class:

public class ClassAB
{
    [Required]
    [MaxLength(100)]
    [DataType(DataType.Text)]
    public string A{ get; set; }

    [Required]
    [MaxLength(100)]
    [DataType(DataType.MultilineText)]
    public string B{ get; set; }
}

My home controller:

    [HttpPost]
    public ActionResult MyMethod(ClassAB classObject)
    {}

and my Javacript call

let data = {           
      "A": "A",
      "B": "B"          
}

await fetch(`https://localhost:44359/Home/MyMethod/`, {
            method: "POST",
            body: JSON.stringify(data),
            contentType:"application/json", 
            success: (result)=>{
                console.log(result)
            },
            failure: (result) => {
                alert(result)
            }
        });

Upvotes: 0

Views: 54

Answers (3)

Eric Herlitz
Eric Herlitz

Reputation: 26257

WebAPI won't know to model bind an object like that. See https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

Try using the [FromBody] attribute

[HttpPost]
public ActionResult MyMethod([FromBody] ClassAB classObject)
{}

When combining this with a proper javascript post this will work, see image.

enter image description here

Sample js

<script>
    var xhr = new XMLHttpRequest();
    var url = "https://localhost:5001/api/default/MyMethod";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            console.log(json.email + ", " + json.password);
        }
    };
    var data = JSON.stringify({ "A": "A", "B": "B" });
    xhr.send(data);
</script>

Upvotes: 0

MeeraWeeks
MeeraWeeks

Reputation: 93

Found the issue. My contentType should have been in header. Modifying request to

await fetch(`https://localhost:44359/Home/MyMethod/`, {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                 'Content-Type': 'application/json'
            },
            success: (result)=>{
                console.log(result)
            },
            failure: (result) => {
                alert(result)
            }
        });

fixed the issue

Upvotes: 1

JohnMathew
JohnMathew

Reputation: 528

Try this

       var data = [{A: 'A',B:'B'}];       
       await fetch(`https://localhost:44359/Home/MyMethod/`, {
                method: "POST",
                body: JSON.stringify(data),
                contentType:"application/json", 
                success: (result)=>{
                    console.log(result)
                },
                failure: (result) => {
                    alert(result)
                }
            });

        [HttpPost]
        public ActionResult MyMethod(List<ClassAB > classObject)
        {}

Upvotes: 0

Related Questions