I have a table full of input text they look like this:
<input type='text' value='{Value}' id='{Model.ID}' class='ChckNumber' />
the class name is different based off what column it is, the Model.ID is different based off the row and the column is different based off the column and row.
When the input text becomes unfocused I call an api to update the value with what the user entered like so:
$("input[type=text]").on("focusout", function () {
var id = $(this).attr("id");
var column = $(this).attr("class");
var value = $(this).val();
if (typeof id !== "undefined" && typeof column !== "undefined" && typeof value !== "undefined") {
$.ajax({
url: "/api/Action/UpdateTable?id=" + id + "&column=" + column + "&value=" + value,
type: "GET",
error: function (request, status, error) {
InsertLogEntry(request.responseText + " From API Call /api/Action/UpdateTable");
},
success: function (data) {
}
});
}
});
Here is the API Controller its calling:
[HttpGet]
public void UpdateTable(int id, string column, string value)
{
MethodClass method = new MethodClass();
if(column != null && column != "" && id != 0)
{
method.UpdateTable(id, column, value);
}
}
and here is the method call I am making:
public void UpdateTable(int id, string column, string value)
{
connection = new SqlConnection(connectionString);
if(column.Contains("Date"))
{
DateTime dt = Convert.ToDateTime(value);
command = new SqlCommand("UPDATE tblCheckTrackerRegister SET " + column + " = @Date WHERE ID = " + id);
command.Parameters.Add("@Date", System.Data.SqlDbType.DateTime);
command.Parameters["@Date"].Value = dt.Equals(DateTime.MinValue) ? (object)DBNull.Value : dt;
}
else
{
int result;
if (int.TryParse(value, out result))
{
command = new SqlCommand("UPDATE table SET " + column + " = " + value + " WHERE ID = " + id);
}
else
{
command = new SqlCommand("UPDATE table SET " + column + " = '" + value + "' WHERE ID = " + id);
}
}
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
This works well, but I am looking to improve it. I honestly believe there must be a better way to go about this as my code seems messy to me, My question is, can anyone suggest another way to go about what I am trying to accomplish?