最近的項目中,因爲頁面有很多textbox需要取值,而且有些數據需要判斷是否爲空,還需要做正則校驗,如果是單個單個的取感覺就很麻煩,所以就想要循環獲取控件,再來根據控件中的屬性來判斷是否需要判斷非空、正則校驗以及輸出異常。
首先是前臺
<table runat="server" id="table">
<tr>
<td>
<span>*</span>聯係方式
</td>
<td>
<!--我這裏是使用的html中data屬性來定義的一些需要用到的值-->
<!--比如數據庫對應的欄位,正則表達式,描述,和正則校驗沒有匹配時輸出的異常信息-->
<asp:TextBox runat="server" ID="tb_tel" CssClass="form-control"
data-column="PHONENO" data-reg="^1[345789]\d{9}$"
data-regException="手機號碼格式不正確" data-desc="聯係方式"
placeholder="請輸入11位手機號碼"/>
</td>
</tr>
</table>
後臺用的是遞歸,並使用Dictionary來存儲獲取到的值
// <summary>
/// 循環獲取textbox和ddl的值
/// 適用於控件多的時候
/// </summary>
/// <param name="control"></param>
public Dictionary<string, object> GetControl(Control control, Dictionary<string, object> dic) {
//Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (Control c in control.Controls) {
if (control.HasControls()) {
GetControl(c,dic);
}
if (c is TextBox) {
//如果是textbox
//先判斷是否有輸入
//再判斷是否有data-reg屬性
//如果有則使用正則表達式進行判斷
//將數據添加到dictionary
TextBox text = (TextBox)c;
string column = text.Attributes["data-column"];
object value = TextBoxOperate(text);
dic.Add(column, value);
}
else if (c is DropDownList) {
DropDownList ddl = (DropDownList)c;
string column = ddl.Attributes["data-column"];
string value = ddl.SelectedValue;
dic.Add(column, value);
}
}
return dic;
}
private object TextBoxOperate(TextBox tb) {
string value = tb.Text.Trim();
//如果數據爲空並且不允許爲空的時候則拋出錯誤。頁面中的控件如果沒有data-allowNull的則表示默認不能爲空
if (string.IsNullOrEmpty(value) && !tb.Attributes["data-allowNull"].Equals("Y"))
throw new ArgumentNullException(tb.Attributes["data-desc"] + "不能爲空");
//正則校驗
if (tb.Attributes["data-reg"] != null) {
string reg = tb.Attributes["data-reg"];
if (!CheckDataByRegex.CheckData(reg, value)) {
throw new FormatException(tb.Attributes["data-regException"]);
}
}
//根據實際情況來轉換數據類型
string type = tb.Attributes["data-type"];
return ConvertValue(type, value);
}
/// <summary>
/// 通過正則表達式驗證數據
/// </summary>
/// <param name="regStr"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool CheckData(string regStr,string value) {
//如果正則表達式是空的,則直接返回true
if (string.IsNullOrEmpty(regStr))
return true;
Regex reg = new Regex(regStr);
return reg.IsMatch(value);
}
/// <summary>
/// 根據類型轉換數據
/// </summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <returns></returns>
private object ConvertValue(string type, string value) {
object res = new object();
switch (type) {
case "int":
res = int.Parse(value);
break;
case "decimal":
res = decimal.Parse(value);
break;
case "date":
res = DateTime.Parse(value);
break;
case null:
case "string":
default:
res = value;
break;
}
return res;
}
good good study,day day up!有錯誤和不足的地方,還請指出來,我好修改,三克油