在搜索中的Request.Form控制/解析的NameValueCollection [英] Searching for controls in Request.Form / Parsing a NameValueCollection
问题描述
我在寻找控制的名称使用的Request.Form。
I am searching for control names using Request.Form.
当然,我知道你可以使用AllKeys遍历所有值,你可以做表[控件名称]为好。
Of course I know you can can iterate around all values using AllKeys, and you can do Form["controlName"] as well.
但我的一些控件的名称是动态的,这将是能够做的东西一样有用的:
However some of my control names are dynamic and it would be useful to be able to do stuff like:
1)获得控件的子集卫生组织名集合中具有一定的preFIX启动 2)搜索与模式匹配的控件名称,因为你将与一个普通的前pression做的。
1)Getting a subset of controls in the collection whos name start with a certain prefix 2) Search for control names that match a pattern, as you would do with a regular expression.
但没有办法,我可以看到做这样的东西。
But there is no way I can see to do stuff like this.
注:我知道如何使用的FindControl为ASP.NET控件,但这些都是标准的HTML。
N.B I know how to use FindControl for ASP.NET controls but these are standard HTML.
推荐答案
如果您使用C#3你可以使用LINQ和扩展方法的一个很好的方式来实现这一目标。首先,你需要创建设计由布赖恩·沃茨在<一个扩展方法href="http://stackoverflow.com/questions/391023/make-namevaluecollection-accessible-to-linq-query">this螺纹:
If you are using C#3 you can use LINQ and extension methods to achieve this in a very nice way. First you need to create an extension method devised by Bryan Watts in this thread:
public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));
}
现在,说你有这样的形式:
Now, say you had a form like this:
<form id="form1" runat="server">
<div>
<input type="text" name="XXX_Name" value="Harold Pinter" />
<input type="text" name="XXX_Email" value="harold@example.com" />
<input type="text" name="XXX_Phone" value="1234 5454 5454" />
<input type="text" name="YYY_Name" value="AN. Other" />
<input type="text" name="YYY_Email" value="another@example.com" />
<input type="text" name="YYY_Phone" value="8383 3434 3434" />
<input type="submit" value="submit button" />
</div>
</form>
您可以在您的codebehind做到这一点:
You could do this in your codebehind:
protected void Page_Load(object sender, EventArgs e)
{
var data = Request.Form.ToPairs().Where(k => k.Key.StartsWith("XXX_"));
foreach (var item in data)
{
Response.Write(String.Format("{0} = '{1}', ", item.Key, item.Value));
}
}
这将输出:
XXX_Name = 'Harold Pinter'
XXX_Email = 'harold@example.com'
XXX_Phone = '1234 5454 5454'
这篇关于在搜索中的Request.Form控制/解析的NameValueCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!