JData 使用教程(五) 对输入数据进行验证(服务端验证)
JData 除了可以在客户端验证数据,还可以在服务端对数据进行验证。如下图所示:
服务端代码如下:
代码
[WebMethod]
public ExecuteResult UpdateOrderWithValidate(Dictionary<string, object> item)
{
string freightError = null;
string shipNameError = null;
var Freight = Convert.ToInt32(item["Freight"]);
var ShipName = Convert.ToString(item["ShipName"]);
//Validate the values.
if (Freight > 2)
freightError = "Please enter a value less than or equal to 2.";
if (ShipName == null || ShipName.Length > 5)
shipNameError = "Please enter no more than 5 characters.";
if (freightError != null || shipNameError != null)
{
var message= new { Freight = freightError, ShipName = shipNameError };
return new ExecuteResult { AffectedRowCount = 0, Message = message};
}
//Update the data
return new ExecuteResult { AffectedRowCount = 1 };
}
上面那段代码,首先是对数据进行验证,然后创建一个包含错误信息的匿名对象,并将请对象赋值给 ExecuteResult 的 Message 成员,以便将错误信息返回到客户端,而 AffectedRowCount = 0 表示更新失败。该匿名对象的成员名称必须与验证对象的属性对应。
也就是下面这条语句。
var message = new { Freight = freightError, ShipName = shipNameError };
return new ExecuteResult { AffectedRowCount = 0, Message = message };
客户端的脚本如下:
代码
Sys.onReady(function() {
var o = new WebApplication.OrderMetaType();
var dataSource = new JData.WebServiceDataSource("../Services/NorthwindService.asmx", "GetOrders", null, "UpdateOrderWithValidate");
dataSource.set_selector([o.OrderID, String.format('{0} + " " + {1} as EmployeeName', o.Employee.FirstName, o.Employee.LastName), o.Freight, o.ShipName]);
var col1 = new JData.BoundField(o.OrderID, null, '80px', null, true);
var col2 = new JData.BoundField('EmployeeName', null, '120px', '112px', true);
var col3 = new JData.BoundField(o.Freight, null, '80px', '72px');
var col4 = new JData.BoundField(o.ShipName, null, '220px');
var col5 = new JData.CommandField();
col5.set_showEditButton(true);
col5.set_showCancleButton(true);
col5.get_itemStyle().set_width('90px');
var gridView = new JData.GridView($get('gridView'));
gridView.set_dataSource(dataSource);
gridView.set_columns([col1, col2, col3, col4, col5]);
gridView.set_allowPaging(true);
gridView.set_caption("Validate the value on the server side");
JData.JQueryUIStyle(gridView);
gridView.initialize();
});
完整代码下载以及在线演示请访问 http://jdata.alinq.org