0

I am sending an array of object from a web page to C# via ajax. I am trying to update my table with the array of objects Please help.

This is the controller

public HttpResponseMessage Update([FromBody]List<Model> json)
{
    var result = db.Models.ToList();

    return response;
}

This is the Model class

    public int ID {get; set;}

    public string ModelNumber { get; set; }

    public string Category { get; set; }

    public string PartNumber { get; set; }

Here is a sample of the json array

var json = [{ID:1,ModelNumber: gw234, Category: A, Partnumber: rty466m},{ID:2,ModelNumber: kw274, Category: B, Partnumber: tbg55},{ID:3,ModelNumber: gr456, Category: A, Partnumber: htg555}]

3 Answers 3

2

Assuming array of objects are type Entity(Model), you could set the entity state to modified

json.ForEach(m=> db.Entry(m).State = EntityState.Modified);

db.SaveChnages();

For more information check this out https://msdn.microsoft.com/en-us/data/jj592676.aspx

Sign up to request clarification or add additional context in comments.
1
 using System.Data.Entity.Migrations;  

 public HttpResponseMessage Update([FromBody]List<Model> json)
    {
        var result = db.Models.ToList();

        // create object from dbContext
        var db = new MyDbContext();

        // add entities on dbContext,
        db.SomeRepo.AddOrUpdate(json); 
        // commit the change on db
        db.Save();  

        return response;
    }

AddOrUpdate method is in under using System.Data.Entity.Migrations; if entity has id ,it will execute update else add

cheers

Comments

-1

Please follow the below link.

Updating Related Data with the Entity Framework in an ASP.NET MVC Application

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.