I am trying to update the information that is deserialised from my JSON file. The list is populated in an editable asp.net form and I would like to edit the item and then update the JSON file. When I make the changes it Adds a new file to the list instead of updating the original. How can I make it update instead of adding.
Thanks in advance!
public partial class EditBook : System.Web.UI.Page
{
Catalogue catalogueInstance;
//Filepath for json file
const string FILENAME =
@"C:\Users\tstra\Desktop\19456932_CSE2ICX_Assessment_3\Bin\Books.json";
protected void Page_Load(object sender, EventArgs e)
{
// reading data contained in the json filepath
string jsonText = File.ReadAllText(FILENAME);
//convert objects in json file to lists
catalogueInstance = JsonConvert.DeserializeObject<Catalogue>(jsonText);
ddlEdit.DataSource = catalogueInstance.books;
ddlEdit.DataTextField = "title";
ddlEdit.DataValueField = "id";
//binding the data to Drop Down List
ddlEdit.DataBind();
}
protected void btnSubmit_editBook(object sender, EventArgs e)
{
int id = Int32.Parse(txtID.Text);
string title = txtTitle.Text;
int year = Int32.Parse(txtYear.Text);
string author = txtAuthor.Text;
string publisher = txtPublisher.Text;
string isbn = txtISBN.Text;
catalogueInstance.books.Add(new Book(id, title, author, year, publisher,
isbn));
string jsonText = JsonConvert.SerializeObject(catalogueInstance);
File.WriteAllText(FILENAME, jsonText);
txtSummary.Text = "Book ID of " + id + " Has Been Updated in the
Catalogue" + Environment.NewLine;
}
protected void ddlEdit_SelectedIndexChanged(object sender, EventArgs e)
{
Book b = catalogueInstance.books[ddlEdit.SelectedIndex];
txtID.Text = b.id.ToString();
txtTitle.Text = b.title;
txtAuthor.Text = b.author;
txtYear.Text = b.year.ToString();
txtPublisher.Text = b.publisher;
txtISBN.Text = b.isbn;
}
}