Home > database >  ASP Web APi - Post list
ASP Web APi - Post list

Time:12-22

Im working on a project to record skills for software engineers. Multiple skills are to be logged with their corresponding score for each submission an engineer will make.

My Model

public partial class Score
{
    public int Id { get; set; }
    public int User { get; set; }
    public int SubmissionPeriod { get; set; }
    public int Capability { get; set; }
    public byte Score1 { get; set; }
}

My Web API Post:

[HttpPost]
public async Task<ActionResult<Score>> PostScore(Score score)
{
    _context.Scores.Add(score);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetScore", new { id = score.Id }, score);
}

My Calling UI:

public ActionResult NewSubmission(ScoreModel  newScoreSubmission)
{

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Baseurl   "/api/Scores/PostScore");

        //HTTP POST
        var postTask = client.PostAsJsonAsync<ScoreModel>(client.BaseAddress, newScoreSubmission);
        postTask.Wait();

        var result = postTask.Result;
        if (result.IsSuccessStatusCode)
        {
            return RedirectToAction("ListScores");
        }
        else
        { //ModelState.AddModelError(string.Empty, "An Error Occured in 'public ActionResult NewCapability'- Please contact Dev Support ");
        }
    }



    return View(newScoreSubmission);
}

The issue is clearly this is set up for single entry. So one 'Score' per call to the Web API. Im sure I need to somehow pass a list of the Score Object but despite reading a few articles im getting very lost and very confused..

hoping you guys can help out and show me where im going wrong or what the code might look like..

thanks for reading..

CodePudding user response:

You need to change the method to take a list.

[HttpPost]
public async Task<ActionResult<List<Score>>> PostScore(List<Score> scores)
{
    _context.Scores.AddRange(scores);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetScores", scores);
}

And change the UI code accordingly, I am not writing the complete code.

public ActionResult NewSubmission(List<ScoreModel> newScoreSubmissions)
{
    List<Score> scores = new List<Score>();
    foreach (var newScoreSubmission in newScoreSubmissions)
    {
        scores.Add(new Score
        {
            User = newScoreSubmission.User,
            SubmissionPeriod = newScoreSubmission.SubmissionPeriod,
            Capability = newScoreSubmission.Capability,
            Score1 = newScoreSubmission.Score1
        });
    }

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Baseurl   "/api/Scores/PostScore");

        var postTask = client.PostAsJsonAsync<List<Score>>(client.BaseAddress, scores);
        ...
    }

    return View(newScoreSubmissions);
}
  • Related