我正在尝试开发动态jqgrid,其中所有字段都是由数据库使用存储过程驱动的,这很好但我在用户在jqgrid上编辑时保存特定记录时遇到问题。到目前为止我的代码下面..
colNames: colname,
colModel: colmodel,
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list2').restoreRow(lastsel);
jQuery('#list2').editRow(id, true);
lastsel = id;
}
},
serializeRowData: function (postdata) {
return { tab: $(".ui-state-active").attr("id"), Data: JSON.stringify(postdata) }
},
C#
[HttpPost]
public JsonResult Edit(string Data)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var formData = js.Deserialize<object>(Data) as IDictionary<string, object>;
List<SqlParameter> SQLParm = new List<SqlParameter>();
foreach (var item in formData)
{
if (item.Key != "oper")
{
SqlParameter param = new SqlParameter();
param.ParameterName = "@" + item.Key;
param.Value = item.Value;
SQLParm.Add(param);
}
}
return null;
}
现在我因为动态jqgrid而被卡住,它返回各种数据,我创建了一个列表然后传递给SP,但问题是存储过程将如何计算这些参数?
我可以选择其他方式吗?
答案 0 :(得分:0)
据推测,您的数据是动态的,但您知道可以是什么(否则,您的过程如何知道如何处理它?)。如果是这样,您可以使用表值参数[TVP](自定义用户表类型,其中包含过程可能需要接收的所有属性)。然后,您可以在发送到存储过程之前填充适用的属性。
有关TVP的更多信息:http://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx
用法:
[HttpPost]
public JsonResult Edit(string Data)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var formData = js.Deserialize<object>(Data) as IDictionary<string, object>;
List<SqlDataRecord> sqlDataRecords = new List<SqlDataRecord>();
foreach (var item in formData)
{
// Create sql data record with appropriate properties populated and add to list if applicable
}
SqlParameter[] sqlParameters = new SqlParameter("YourTableTypeParamName", SqlDbType.Structured)
{
Value = sqlDataRecords,
TypeName = "dbo.YourTableType"
};
SqlConnection conn = ... // define connection here
try
{
using (SqlCommand command = conn.CreateCommand())
{
command.Connection = conn;
conn.Open();
command.CommandText = "YourStoredProcedureName";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddRange(sqlParameters);
using (DbDataReader reader = command.ExecuteReader())
{
// Do something with results
}
}
}
finally
{
conn.Close();
}
return null;
}