Edit operation not saving to the DB












0















I posted the question earlier, but didn't receive any correct responses, hence posting again with some edits. I have a function that accepts two parameters, IDs and Dates. When I had put breakpoints, I was able to see the Ids and the Dates selected on the page as parameter values. However, after hitting the process button, nothing happens, meaning this data isn't getting saved to the DB.



Model Classes:



public class Hello{

public string ID{ get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date{ get; set; }

}


Controller Class:



  [HttpGet]
public ActionResult Selection(string ids, string dates)
{
model = new Hello();
ExtensionDB db = new ExtensionDB();
string IDS = ids.Split(',');
string DATES = dates.Split(',');
List<Hello> list = new List<Hello>();
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { ID = IDS[i], Date = DateTime.Parse(DATES[i]) };
list.Add(item);
}
}

if (ModelState.IsValid)
{
foreach (var row in db.Table1)
{
foreach (var row2 in db.Table2)
{
if (row.UID== row2.CID) // UID and CID are Foreign keys that join these two tables
{
foreach (var item in list)
{
if (row.UID == Convert.ToInt32(item.ID))
{
row2.ReportedDate = item.Date;
}
db.SaveChanges();
}
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}


I will add the view class if needed, however the problem is here.. You can also refer to it here: Saving changes to the DB MVC










share|improve this question

























  • In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

    – Paul Abbott
    Nov 27 '18 at 22:20











  • You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

    – Hooman Bahreini
    Nov 27 '18 at 23:40













  • Posted the edits guys

    – caitlinp
    Nov 28 '18 at 14:49
















0















I posted the question earlier, but didn't receive any correct responses, hence posting again with some edits. I have a function that accepts two parameters, IDs and Dates. When I had put breakpoints, I was able to see the Ids and the Dates selected on the page as parameter values. However, after hitting the process button, nothing happens, meaning this data isn't getting saved to the DB.



Model Classes:



public class Hello{

public string ID{ get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date{ get; set; }

}


Controller Class:



  [HttpGet]
public ActionResult Selection(string ids, string dates)
{
model = new Hello();
ExtensionDB db = new ExtensionDB();
string IDS = ids.Split(',');
string DATES = dates.Split(',');
List<Hello> list = new List<Hello>();
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { ID = IDS[i], Date = DateTime.Parse(DATES[i]) };
list.Add(item);
}
}

if (ModelState.IsValid)
{
foreach (var row in db.Table1)
{
foreach (var row2 in db.Table2)
{
if (row.UID== row2.CID) // UID and CID are Foreign keys that join these two tables
{
foreach (var item in list)
{
if (row.UID == Convert.ToInt32(item.ID))
{
row2.ReportedDate = item.Date;
}
db.SaveChanges();
}
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}


I will add the view class if needed, however the problem is here.. You can also refer to it here: Saving changes to the DB MVC










share|improve this question

























  • In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

    – Paul Abbott
    Nov 27 '18 at 22:20











  • You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

    – Hooman Bahreini
    Nov 27 '18 at 23:40













  • Posted the edits guys

    – caitlinp
    Nov 28 '18 at 14:49














0












0








0








I posted the question earlier, but didn't receive any correct responses, hence posting again with some edits. I have a function that accepts two parameters, IDs and Dates. When I had put breakpoints, I was able to see the Ids and the Dates selected on the page as parameter values. However, after hitting the process button, nothing happens, meaning this data isn't getting saved to the DB.



Model Classes:



public class Hello{

public string ID{ get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date{ get; set; }

}


Controller Class:



  [HttpGet]
public ActionResult Selection(string ids, string dates)
{
model = new Hello();
ExtensionDB db = new ExtensionDB();
string IDS = ids.Split(',');
string DATES = dates.Split(',');
List<Hello> list = new List<Hello>();
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { ID = IDS[i], Date = DateTime.Parse(DATES[i]) };
list.Add(item);
}
}

if (ModelState.IsValid)
{
foreach (var row in db.Table1)
{
foreach (var row2 in db.Table2)
{
if (row.UID== row2.CID) // UID and CID are Foreign keys that join these two tables
{
foreach (var item in list)
{
if (row.UID == Convert.ToInt32(item.ID))
{
row2.ReportedDate = item.Date;
}
db.SaveChanges();
}
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}


I will add the view class if needed, however the problem is here.. You can also refer to it here: Saving changes to the DB MVC










share|improve this question
















I posted the question earlier, but didn't receive any correct responses, hence posting again with some edits. I have a function that accepts two parameters, IDs and Dates. When I had put breakpoints, I was able to see the Ids and the Dates selected on the page as parameter values. However, after hitting the process button, nothing happens, meaning this data isn't getting saved to the DB.



Model Classes:



public class Hello{

public string ID{ get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date{ get; set; }

}


Controller Class:



  [HttpGet]
public ActionResult Selection(string ids, string dates)
{
model = new Hello();
ExtensionDB db = new ExtensionDB();
string IDS = ids.Split(',');
string DATES = dates.Split(',');
List<Hello> list = new List<Hello>();
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { ID = IDS[i], Date = DateTime.Parse(DATES[i]) };
list.Add(item);
}
}

if (ModelState.IsValid)
{
foreach (var row in db.Table1)
{
foreach (var row2 in db.Table2)
{
if (row.UID== row2.CID) // UID and CID are Foreign keys that join these two tables
{
foreach (var item in list)
{
if (row.UID == Convert.ToInt32(item.ID))
{
row2.ReportedDate = item.Date;
}
db.SaveChanges();
}
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}


I will add the view class if needed, however the problem is here.. You can also refer to it here: Saving changes to the DB MVC







asp.net-mvc entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 30 '18 at 15:38







caitlinp

















asked Nov 27 '18 at 22:03









caitlinpcaitlinp

677




677













  • In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

    – Paul Abbott
    Nov 27 '18 at 22:20











  • You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

    – Hooman Bahreini
    Nov 27 '18 at 23:40













  • Posted the edits guys

    – caitlinp
    Nov 28 '18 at 14:49



















  • In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

    – Paul Abbott
    Nov 27 '18 at 22:20











  • You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

    – Hooman Bahreini
    Nov 27 '18 at 23:40













  • Posted the edits guys

    – caitlinp
    Nov 28 '18 at 14:49

















In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

– Paul Abbott
Nov 27 '18 at 22:20





In the code above, at no point are you adding or updating database entities. What does getStuff do, and what is the point of looping over the results?

– Paul Abbott
Nov 27 '18 at 22:20













You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

– Hooman Bahreini
Nov 27 '18 at 23:40







You are not adding anything to your DB, and you have not included the code for DB, so we cannot help you with the current code

– Hooman Bahreini
Nov 27 '18 at 23:40















Posted the edits guys

– caitlinp
Nov 28 '18 at 14:49





Posted the edits guys

– caitlinp
Nov 28 '18 at 14:49












1 Answer
1






active

oldest

votes


















0














Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..



First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:



{ 
id = rid,
date = date
}


and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:



public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}


In the ajax call instead of:



data: { ids: ids, dates: dates },


you'll want something like:



data: { updates: updateData }, 


where updateData is your collection of id + date pairs.



and use that view model in your method:
public ActionResult Process(IList updates)



Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")



Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.



public ActionResult Process(IList<UpdateDateViewModel> updates) 
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...

foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}


Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.



Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.



Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.






share|improve this answer
























  • My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

    – caitlinp
    Nov 28 '18 at 14:49











  • Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

    – caitlinp
    Nov 28 '18 at 17:11











  • The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

    – Steve Py
    Nov 28 '18 at 21:26











  • Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

    – caitlinp
    Nov 30 '18 at 15:42











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53508912%2fedit-operation-not-saving-to-the-db%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..



First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:



{ 
id = rid,
date = date
}


and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:



public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}


In the ajax call instead of:



data: { ids: ids, dates: dates },


you'll want something like:



data: { updates: updateData }, 


where updateData is your collection of id + date pairs.



and use that view model in your method:
public ActionResult Process(IList updates)



Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")



Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.



public ActionResult Process(IList<UpdateDateViewModel> updates) 
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...

foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}


Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.



Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.



Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.






share|improve this answer
























  • My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

    – caitlinp
    Nov 28 '18 at 14:49











  • Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

    – caitlinp
    Nov 28 '18 at 17:11











  • The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

    – Steve Py
    Nov 28 '18 at 21:26











  • Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

    – caitlinp
    Nov 30 '18 at 15:42
















0














Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..



First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:



{ 
id = rid,
date = date
}


and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:



public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}


In the ajax call instead of:



data: { ids: ids, dates: dates },


you'll want something like:



data: { updates: updateData }, 


where updateData is your collection of id + date pairs.



and use that view model in your method:
public ActionResult Process(IList updates)



Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")



Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.



public ActionResult Process(IList<UpdateDateViewModel> updates) 
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...

foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}


Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.



Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.



Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.






share|improve this answer
























  • My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

    – caitlinp
    Nov 28 '18 at 14:49











  • Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

    – caitlinp
    Nov 28 '18 at 17:11











  • The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

    – Steve Py
    Nov 28 '18 at 21:26











  • Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

    – caitlinp
    Nov 30 '18 at 15:42














0












0








0







Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..



First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:



{ 
id = rid,
date = date
}


and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:



public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}


In the ajax call instead of:



data: { ids: ids, dates: dates },


you'll want something like:



data: { updates: updateData }, 


where updateData is your collection of id + date pairs.



and use that view model in your method:
public ActionResult Process(IList updates)



Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")



Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.



public ActionResult Process(IList<UpdateDateViewModel> updates) 
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...

foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}


Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.



Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.



Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.






share|improve this answer













Your code does not attempt to update anything. Start with confirming what the data you are passing to this POST call contains, and what you want to do with it. It looks like what you are trying to do is update the dates for a number of records. Looking at your previous post (no need to re-post another question with the same code) there are a few things..



First: Structure the data you want to pass to the POST call into a collection of simple objects containing an id and a date. For example:



{ 
id = rid,
date = date
}


and add those to the collection named something like "updateData" rather than two separate arrays of IDs and dates. Then in the server-side code, declare a simple view model class:



public class UpdateDateViewModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
}


In the ajax call instead of:



data: { ids: ids, dates: dates },


you'll want something like:



data: { updates: updateData }, 


where updateData is your collection of id + date pairs.



and use that view model in your method:
public ActionResult Process(IList updates)



Provided that request data is sent as Json, ASP.Net should translate that data automatically for you, though you may need to configure ASP.Net to translate the camelCase vs PascalCase. Worst case, to test, you can use camelCase property names ("id" and "date")



Now when it comes to updating the data: Server side, please get in the habit of using meaningful variable names, not "c", "i", etc. It makes code a lot easier to understand.



public ActionResult Process(IList<UpdateDateViewModel> updates) 
{
using (db = new DB())
{
//rp = new RequestProcess(); - Assuming RequestProcess is an Entity?
//var c = rp.getStuff(); - No idea what this getStuff() method does...

foreach(var update in updates)
{
var request = db.RequestProcesses.Find(update.Id);
if (request != null)
request.RequestDate = update.Date; // If we find a matching request, update it's date.
else
{ // Doesn't exist, create it and add it to the DbSet.(table)
var request = new RequestProcess { Id = update.Id, RequestDate = update.Date };
db.RequestProcesses.Add(request);
}
db.SaveChanges();
}
}
}


Now this is a very bare bones guess at what you may be trying to do. Ideally though, updates should be completely separate from adds in the sense that an update should only deal with existing records. If it comes across an ID that it cannot find it should throw an error, ignore, and/or return a status to the user that something wasn't right. Creating new entries should be a separate call and ensure that records are properly initialized with their required fields.



Your original code looked to be taking a list of IDs, but then creating a new entity and calling that "getStuff" method that didn't have the DbContext, or any of the values from the POST call, but then attempting to copy values from that entity into the string parameters that you passed (which would overwrite the Json string) None of that would have updated an entity which would never have updated your data.



Take it slow and follow the examples before attempting to adapt them to your ideas. It will be a lot more constructive and less frustrating then writing a bunch of code that doesn't really make much sense, then wondering why it doesn't work. Your original code has probably a dozen or more problems and inefficiencies. Simply pasting it up on Stack will get a lot of confusing comments based on these problems which don't really help with the first issue you want to solve. Strip it back to the minimum, start with getting the data you need to the server in a meaningful way, then from that, attempt to use that data to update your entities.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 28 '18 at 1:15









Steve PySteve Py

5,74011017




5,74011017













  • My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

    – caitlinp
    Nov 28 '18 at 14:49











  • Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

    – caitlinp
    Nov 28 '18 at 17:11











  • The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

    – Steve Py
    Nov 28 '18 at 21:26











  • Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

    – caitlinp
    Nov 30 '18 at 15:42



















  • My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

    – caitlinp
    Nov 28 '18 at 14:49











  • Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

    – caitlinp
    Nov 28 '18 at 17:11











  • The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

    – Steve Py
    Nov 28 '18 at 21:26











  • Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

    – caitlinp
    Nov 30 '18 at 15:42

















My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

– caitlinp
Nov 28 '18 at 14:49





My English isn't that great, so it comes out wrong from what I think and what I post haha... Anyhow thank you for the great answer, I will work on it as you have suggested.. I posted the Edits, if you were confused about the model classes.. and where I was getting the getSuff() method from.

– caitlinp
Nov 28 '18 at 14:49













Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

– caitlinp
Nov 28 '18 at 17:11





Also, I am updating the dates for existing ID's only.. Once those are updated I want to hit the "Submit" button and have it save to the DB. I have check boxes that enable editing for that specific ID being checked. For example, ID =1(Checked), Date = 12/12/2008 and ID = 14 (Checked), Date = 12/15/2008

– caitlinp
Nov 28 '18 at 17:11













The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

– Steve Py
Nov 28 '18 at 21:26





The code above would be the basis of the Submit button action. EF entities are essentially a proxy for the database tables. To do things like validations etc. on the server while you are selecting and editing values you would be dealing with the view models. (VMs) Validation calls can take those VMs, lookup entities to compare/validate, and return feedback. (i.e. error messages) When the VMs are ready to save, pass the valid ones to the submit action to load the applicable entities and copy across the data before a SaveChanges.

– Steve Py
Nov 28 '18 at 21:26













Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

– caitlinp
Nov 30 '18 at 15:42





Posted the edits... I am looping through both tables and checking if their foreign keys match and if the do, then I loop through the list of the items passed into the parameter. After that I want the ID to be checked against the first table and if it exists then update the date.. However this isn't working because the Dates are being saved to Table2 while the ID's are getting picked up from Table1..

– caitlinp
Nov 30 '18 at 15:42




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53508912%2fedit-operation-not-saving-to-the-db%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks