Abhilash Gopalakrishna
Abhilash Gopalakrishna

Reputation: 980

Saving JSON received through a controller to the database MVC

Hi guys I have started to use visual studio from about 4-5 days now, I had a lot of doubts, Thanks to the Stack Overflow Community I have gained a bit more knowledge. I am trying to POST JSON to the controller and save it to a database using Model Binding.

I am able to POST the JSON to the controller using the following ajax:

$.ajax({
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        type: 'GET',
        url: 'https://api.github.com/search/repositories?q=repos+topic:' + $(this).attr('id') + '&sort=stars&order=desc&per_page=10',
        success: function (data) {

        **ajaxresult.push(data);**
        debugger;

        table.empty();
        table.append("<thead><tr><th>Avatar</th><th>Name</th><th>Score</th><th>URL</th><th>Updated at</th></tr></thead>");
        $.each(data.items, function (i, object) {

            var row = $('<tr>').addClass('table-primary');
            row.append('<td><img src=' + object.owner.avatar_url + 'height=50px width=50px/></td>');
            row.append('<td>' + object.name + '</td>' + '<td>' + object.score + '</td>' + '<td>' + object.url + '</td>' + '<td>' + object.updated_at + '</td>');
            table.append(row);

            **ajaxresult[i] = { "Avatar": object.owner.avatar_url, "Name": object.name, "Score": object.score, "URL": object.url, "Updatedat": object.updated_at };**
        });
        **var myJSON = JSON.stringify(ajaxresult);**
        table.append('</table>');
        $('table').replaceWith(table);
        debugger;
        console.log(myJSON);
         $.ajax({

                    contentType: 'application/json; charset=utf-8',
                    datatype:'JSON',
                    type: 'POST',
                    url: 'http://localhost:60294/Git/Updateto',
                    **data: myJSON,**
             success: function (data) {
                 alert('Post Succesful');
                    },
                    error: function (data) {
                        alert('error');
                            }
                 });
    }

});

});

This is my controller and Model:

[HttpPost]
        public async Task<IActionResult> Updateto(GitJSON gitjson)
    {
        if (ModelState.IsValid)
        {
            gitjson.gitdList[0].AvatarURL=;


        }
        await _context.SaveChangesAsync();

        return Ok();
    }

Model:

public class gitd
    {
        public int ID { get; set; }
        public string AvatarURL { get; set; }
        public string Name { get; set; }
        public decimal Score { get; set; }
        public DateTime Updatedat { get; set; }


    }
public class GitJSON
{
    public List<gitd> gitdList { set; get; }
}

My understanding is that in the controller the GitJSON model is being binded. Therefore as a result the JSON pairs are mapped automatically to the public members of the gitd model.

After researching I came to understand that the public List<gitd> gitdList { set; get; }

corresponds to a list of objects which are indexed.Therefore I assume that gitjson.gitdList[0].AvatarURL=; is now referring to the AvatarURL property of the first JSON object I have passed. Is my understanding correct? If true how do I now save the JSON to the database.

Also if I put return View(); in the Updateto controller I get a 500 error. I have not added a view to the Updateto controller.Can this be the only reason ? Also if true, shouldn't it be a Not found error instead of 500 error?

I added a dummy view to the Updateto controller but still return view(); gives a 500 error.

Upvotes: 1

Views: 2381

Answers (1)

Dongdong
Dongdong

Reputation: 2498

  1. Welcome to club MVC
  2. you cannot return a view that does not exist, especially when client expect a json response
  3. you need to map your changes to context, then you can save them

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Updateto(GitJSON gitjson)
    {
        try
        {
            if (ModelState.IsValid)
            {
                //here is sample code to map changes to entities
                var gitdIds = gitjson.gitdList.Select(x => x.Id).ToList;
    
                _context.gitds
                    .Where(x => gitdIds.Contains(x.Id))
                    .ToList()
                    .ForEach(x =>
                    {
                        //find match data
                        var change= data.gitdList.FirstOrDefault(d => d.Id == x.Id);
                        //update your fields here
                        x.Name = change.Name;
                                ...
    
                    });
    
                 //save changes after updated entities
                await _context.SaveChangesAsync();
            }
            return Ok();
        }
        catch (Exception ex)
        {
            return Json(new
            {
                error = ex.Message// or ex.ToString()
            });
    
            // or return RedirectToPage("Error", ex);
        }
    }
    

Upvotes: 1

Related Questions