Currently I have an insert query to my table and I don't have any idea how I can validate it, if the data is already exists in the table.
So for now I just used try-catch to handle the duplicate entry. I just wondering if I could return some text If value goes to catch then display it to my view as alert or something.
Here is my query from controller:
public ActionResult AddUser(int id, string name, string age)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string sqlQuery = "INSERT INTO myTable (id, name, age) VALUES (@id, @name, @age)";
MySqlCommand cmd = new MySqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@age", age);
con.Open();
try {
cmd.ExecuteNonQuery();
con.Close();
return RedirectToAction("Index");
}
catch (Exception )
{
con.Close();
return this.Json("This Data already exist on table");
}
}
}
And this is my script to read my controller query:
function add(id, name, age) {
var result = confirm("Are you want to add " + name + " to list?");
if (result == true) {
$.ajax({
url: '/Home/AddUser',
type: 'POST',
data: {
'id': id,
'name': name,
'age': age,
},
success: function (data) {
alert('Data has been successfully added');
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
}
So far I can successfully insert it to my table but if there is already exist and it's a duplicate it will do nothing so the user will not have a prompt if they already added it or already exist or not.
Any suggestions or comments. TIA.