use*_*331 10 asp.net ajax jquery
我有一个充满输入文本的表,它们看起来像这样:
<input type='text' value='{Value}' id='{Model.ID}' class='ChckNumber' />
Run Code Online (Sandbox Code Playgroud)
类名称根据它是什么列而不同,Model.ID根据行而不同,并且列基于列和行是不同的.
当输入文本变得没有聚焦时,我调用api来更新用户输入的值,如下所示:
$("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) {
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
这是API控制器的调用:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在制作的方法调用:
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();
}
Run Code Online (Sandbox Code Playgroud)
这很好用,但我希望改进它.我真的相信必须有一个更好的方法来解决这个问题,因为我的代码对我来说似乎很混乱.我的问题是,有人能提出另一种方法来解决我想要实现的目标吗?
尝试在 JS 代码中定义一组条件以根据列定义需要使用多个控制器,如下所示:
$("input[type=text]").on("focusout", function () {
var id = $(this).attr("id");
var column = $(this).attr("class");
var value = $(this).val();
var controler = "UpdateTable";
if(column=='Delete'){
controler = "DeleteTable";
}
if(column=='Mail'){
controler = "SendMail";
}
if (typeof id !== "undefined" && typeof column !== "undefined" && typeof value !== "undefined") {
$.ajax({
url: "/api/Action/" + controler + "?id=" + id + "&column=" + column + "&value=" + value,
type: "GET",
error: function (request, status, error) {
InsertLogEntry(request.responseText + " From API Call /api/Action/" + controler);
},
success: function (data) {
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
157 次 |
最近记录: |