是否可以从查询字符串获取字典?

use*_*366 7 c# query-string asp.net-mvc-4

我的控制器方法如下所示:

public ActionResult SomeMethod(Dictionary<int, string> model)
{

}
Run Code Online (Sandbox Code Playgroud)

是否可以仅使用查询字符串来调用此方法并填充“模型”?我的意思是,键入如下内容:

ControllerName/SomeMethod?model.0=someText&model.1=someOtherText
Run Code Online (Sandbox Code Playgroud)

在我们的浏览器地址栏中。可能吗?

编辑:

看来我的问题被误解了-我想绑定查询字符串,以便自动填充Dictionary方法参数。换句话说-我不想在我的方法中手动创建字典,但是我会用一些自动数学的.NET绑定器来创建它,所以我可以像这样立即访问它:

public ActionResult SomeMethod(Dictionary<int, string> model)
{
    var a = model[SomeKey];
}
Run Code Online (Sandbox Code Playgroud)

是否有自动装订机,足够聪明地做到这一点?

the*_*tor 6

在ASP.NET Core中,可以使用以下语法(不需要自定义绑定程序):

?dictionaryVariableName[KEY]=VALUE
Run Code Online (Sandbox Code Playgroud)

假设您将此作为方法:

public ActionResult SomeMethod([FromQuery] Dictionary<int, string> model)
Run Code Online (Sandbox Code Playgroud)

然后调用以下URL:

?model[0]=firstString&model[1]=secondString
Run Code Online (Sandbox Code Playgroud)

然后,您的词典将被自动填充。带有值:

(0, "firstString")
(1, "secondString")
Run Code Online (Sandbox Code Playgroud)


Tod*_*ton 6

对于.NET Core 2.1,您可以非常轻松地执行此操作。

public class SomeController : ControllerBase
{
    public IActionResult Method([FromQuery]IDictionary<int, string> query)
    {
        // Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

和网址

/Some/Method?1=value1&2=value2&3=value3

它将绑定到字典。您甚至不必使用参数名称查询。

  • 如果您想要两个参数,并且其中一个参数是一个简单的布尔值或不应该出现在该字典中的参数,该怎么办? (4认同)

小智 1

尝试自定义模型活页夹

      public class QueryStringToDictionaryBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var collection = controllerContext.HttpContext.Request.QueryString;
        var modelKeys =
            collection.AllKeys.Where(
                m => m.StartsWith(bindingContext.ModelName));
        var dictionary = new Dictionary<int, string>();

        foreach (string key in modelKeys)
        {
            var splits = key.Split(new[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
            int nummericKey = -1;
            if(splits.Count() > 1)
            {
                var tempKey = splits[1]; 
                if(int.TryParse(tempKey, out nummericKey))
                {
                    dictionary.Add(nummericKey, collection[key]);    
                }   
            }                 
        }

        return dictionary;
    }
}
Run Code Online (Sandbox Code Playgroud)

在控制器操作中在模型上使用它

     public ActionResult SomeMethod(
        [ModelBinder(typeof(QueryStringToDictionaryBinder))]
        Dictionary<int, string> model)
    {

        //return Content("Test");
    }
Run Code Online (Sandbox Code Playgroud)