admin管理员组

文章数量:1405304

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 mented.

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

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 mented.

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; }
}
Share Improve this question edited Oct 28, 2018 at 14:27 Camilo Terevinto 32.1k7 gold badges95 silver badges126 bronze badges asked Oct 28, 2018 at 14:14 Adam GieblAdam Giebl 651 silver badge9 bronze badges 7
  • What does happen? Does you F12 browser dev tools show anything in the console or network tab? Does your controller get hit at all? More input.... – Crowcoder Commented Oct 28, 2018 at 14:17
  • yes, sorry i forgot to mention that, the request returns 400, and the response is : {"":["The input was not valid."]} – Adam Giebl Commented Oct 28, 2018 at 14:18
  • Two things: you are not posting an Id field, which is required; and you could try to use PostArticle([FromForm] Article article) – Camilo Terevinto Commented Oct 28, 2018 at 14:28
  • I think the answer here may help: stackoverflow./questions/46640024/… – Ryan Cogswell Commented Oct 28, 2018 at 14:31
  • @CamiloTerevinto Ok, i added [FromForm] and i made new model where there is not Id at all, now the request returned 200 (ok) but none of the form data actually came into the article model (Title= null, Content=null) – Adam Giebl Commented Oct 28, 2018 at 14:38
 |  Show 2 more ments

1 Answer 1

Reset to default 5

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

本文标签: cHow to send FormData from javascript to ASPNET Core 21 web API using fetchStack Overflow