Adam Giebl
Adam Giebl

Reputation: 45

How to send FormData from javascript to ASP.NET Core 2.1 web API using fetch

i'm trying to create a form that sends FormData object to API controller that serializes the data to Article class, but i cannot get it to work. I have already tried the things that are commented.

this is my HTML:

<form onsubmit="postArticle()">
<input type="type" name="Title" value="" />
<input type="type" name="Content" value="" />
<input type="submit" value="Submit" />
</form>

this is my JS:

<script>

var postArticle = () => {
    event.preventDefault();
    var Article = new FormData(this.event.target);
    console.log([...Article]);
    fetch('/api/Articles', {
        headers: {
            'Content-Type': 'multipart/formdata',
            //'Content-Type': 'application/json'
        },
        method: "POST",
        body: Article
        //body: JSON.stringify(Article)
    })
}
</script>

Controller:

    // POST: api/Articles
    [HttpPost]
    public async Task<IActionResult> PostArticle(Article article)
    {
        string name = article.Title;
        if (!ModelState.IsValid)
        {
            return Ok();
        }

        _context.Article.Add(article);
        await _context.SaveChangesAsync();

        return Ok();
    }

and my Article class:

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Upvotes: 0

Views: 6547

Answers (1)

Adam Giebl
Adam Giebl

Reputation: 45

Works now! The solution is to not set any content-type headers along with adding the [FromForm], thank you all contributing.

part of the solution was at this thread

these are the changes:

var postArticle = () => {
    event.preventDefault();
    var Article = new FormData(this.event.target);
    console.log([...Article]);
    fetch('/api/Articles', {
        method: "POST",
        body: Article
    })
}

// POST: api/Articles
    [HttpPost]
    public async Task<IActionResult> PostArticle([FromForm]Article article)
    {
        string name = article.Title;
        if (!ModelState.IsValid)
        {
            return Ok();
        }

        //_context.Article.Add(article);
        //await _context.SaveChangesAsync();

        return Ok(); //CreatedAtAction("GetArticle", new { id = article.Id }, article);
    }

Upvotes: 4

Related Questions