我的 C# MVC4 应用程序中有一个表单集合。在此集合的 index[0]
中,有一个字符串的格式始终如 "10=on&13=on&15=on"
;唯一的区别是字符串中 #=on
的数量。
我想从这个字符串中提取每个数字并将它们添加到一个整数列表中。这样做最简单的方法是什么?是否需要正则表达式?
最佳答案
What would be the simplest method of doing this?
我会使用自定义模型 Binder :
public class MyModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.RequestContext.HttpContext.Request.Params;
var keys =
from key in request.Keys.Cast<string>()
where request[key] == "on"
select key;
var onValues = new List<int>();
foreach (var key in keys)
{
int value;
if (int.TryParse(key, out value))
{
onValues.Add(value);
}
}
return onValues.ToArray();
}
}
然后是这样的 Controller 操作:
public ActionResult SomeAction([ModelBinder(typeof(MyModelBinder))]int[] values)
{
return View();
}
现在您可以简单地将以下请求发送到此 Controller 操作,自定义模型绑定(bind)器将完成这项工作:
/SomeAction?10=on&13=on&15=on
Is Regex required?
不不不不不不。
关于c# 表单集合值到 Int 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003937/