For my own project i want to be able to delete tip articles, this works. but know i have the problem that it also deletes tip articles that don't exist. does someone know how to fix this?
code in the tip article manager:
*//Delete tip article in db
public bool DeleteTipArticle(int articleNumber)
{
FillTipArticleList();
return tipArticleDB.DeleteDb(articleNumber);
}*
code in the database:
//Delete the tip article for the tiparticle database
public bool DeleteDb(int articleNumber)
{
MySqlConnection connection = new MySqlConnection(databaseConnection);
//Sql string for deleting the tip article
string sql = "DELETE FROM tiparticle WHERE ArticleNumber = @ArticleNumber";
MySqlCommand command = new MySqlCommand(sql, connection);
command.Parameters.AddWithValue("@ArticleNumber", articleNumber);
try
{
connection.Open();
int amount = command.ExecuteNonQuery();
return amount > 0;
}
catch (MySqlException ex)
{
return false;
}
catch (FormatException ex)
{
return false;
}
catch (NullReferenceException ex)
{
return false;
}
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
code behind the razor page:
[Authorize(Roles = "admin")]
public class DeleteTipArticleModel : PageModel
{
[BindProperty]
public int articleNumber { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
string message = "The tip article has been deleted!";
ViewData["Message"] = message;
TipArticleManager deleteToTipArticleDatabase = new TipArticleManager();
deleteToTipArticleDatabase.DeleteTipArticle(articleNumber);
return Page();
}
else
{
ViewData["Message"] = "Please enter all data fields";
return Page();
}
}
}
i think that i have to do something with the amount > 0 that gets returned, but i am not sure where and how to do this.
CodePudding user response:
You can check the return value of bool succeeded = deleteToTipArticleDatabase.DeleteTipArticle(articleNumber);
to check for amount > 0.
[Authorize(Roles = "admin")]
public class DeleteTipArticleModel : PageModel
{
[BindProperty]
public int articleNumber { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (ModelState.IsValid)
{
TipArticleManager deleteToTipArticleDatabase = new TipArticleManager();
bool succeeded = DeleteToTipArticleDatabase.DeleteTipArticle(articleNumber);
if(succeeded)
{
string message = "The tip article has been deleted!";
ViewData["Message"] = message;
}
return Page();
}
else
{
ViewData["Message"] = "Please enter all data fields";
return Page();
}
}
}
Otherwise you could make a database call for the article number to see if it is already present.