Can I loop through a Collection.Request.Form?
I have some checkboxes with a unique id. is it possible to find all the checkbox+uniquenum in a form collection?
something l开发者_StackOverflow社区ike -
foreach (var item in Collection.Request.Form["checkbox" + with UniqueIDNum])
{
//code
}
No.
Instead, you can loop through all of the keys, and check whether they start with checkbox
.
For example:
foreach(string key in Request.Form) {
if (!key.StartsWith("checkbox")) continue;
...
}
The NameValueCollection enumerator returns keys as strings.
Or something like that
var checkBoxes = Request.Form.Keys.Where(rs=>rs.StartsWith("dummy"));
foreach(string key in checkBoxes){
// Your code
}
You should be able to do this with Linq (this should work, haven't tested): I'm assuming also that the ID of the checkboxes is "checkbox[ID]". BTW, duplicate ID's in form fields is bad bad bad.
var checkboxes = (from key in Request.Form.AllKeys where key = "checkbox" + UniqueIDNum)
foreach(string key in checkboxes)
{
//do stuff
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection fc)
{
string a = fc["hdn_1"].ToString(); // if you know for sure that it will have a value.
string lbl_1 = null;
foreach (var key in fc.AllKeys)
{
if (key.Contains("txt_1"))
{
lbl_1 = fc["txt_1"].ToString();
}
}
}
Hope this helps.
I had to do this in VB.NET, after having not worked with VB.NET in years and even then not having worked with it much, and I used Josh Wolf's answer to get the following:
Dim checkedOrders As IEnumerable(Of String) = From key In Request.Form.AllKeys Where key.StartsWith("chk")
If checkedOrders.Count > 0 Then
' do stuff, loop through checkedOrders, etc
End If
Note that my checkboxes all start with "chk" in the name (e.g. "chk1038", "chk1040", etc).
精彩评论