分析查询字符串数组默认模型联编

分析查询字符串数组默认模型联编

本文介绍了ASP .NET MVC 3基于Facebook的应用程序:分析查询字符串数组默认模型联编?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一言以蔽之:Facebook的经过我的MVC 3应用程序下面的查询字符串后,用户选择朋友一起FB:请求表单控件:

In a nutshell: Facebook passes my MVC 3 application the following query string after a user selects friends with the fb:request-form control:

http://apps.facebook.com/my_app/?...&ids [] = 100001694177427&放大器; IDS [] = 100001178061757

我认为默认的模型绑定将解析查询字符串的ID []数组并将其绑定到我的id参数如下行动:

I assumed the default model binder would parse the ids[] array in the query string and bind it to my ids parameter in the action below:

public ActionResult Index(long[] ids)
{
   //...
   return View();
}

这previous问题似乎备份我的想法:In ASP.NET MVC 2,我可以反序列化查询字符串到一个数组使用默认的模型绑定器?

This previous question appeared to backup my thinking: In ASP.NET MVC 2, can I deserialize a querystring into an array using the default ModelBinder?

不过,我还是收到一个空值。我已经试了每个参数的类型我能想到的,但都无济于事。我可以从我的控制器的ValueProvider看到,它肯定来通过(与被解析为一个数组),所以想通过ModelBinder的源工作之前,我会张贴在这里的想法!

However, I still receive a null value. I've tried every parameter type I can think of, but to no avail. I can see from my controller's ValueProvider that it's definitely coming through (and being parsed as an array), so thought I would post here for ideas before working through the ModelBinder source!

在此先感谢您的帮助。

推荐答案

看着它出现在源寻找包含索引 [0],[1],[2] ... ,而不是允许 [] 。似乎是一个有趣的监督。

Looking at the source it appears to be looking for indexes that contain [0], [1], [2]... rather than allowing for []. Seems an interesting oversight.

不过,你可以通过执行创建自定义ModelBinder的以下内容:

However, you can create a custom modelbinder by doing the following:

public class IdList : List<long> { }

这是一个类来保存我们的IDS

This is a class to hold our ids

public class IdListModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        var x = bindingContext.ValueProvider.GetValue("ids[]");

        IdList list = new IdList();
        foreach (var value in (string[])x.RawValue) {
            //replace this with proper validation of values
            list.Add(long.Parse(value));
        }

        return list;
    }
}

然后在控制器,你会做这样的事情:

Then in the controller you would do something like:

public ActionResult Index(IdList ids) {
    return View();
}

在您的Global.asax您将添加下面一行到你的的Application_Start 方法

In your global.asax you would add the following line to your Application_Start method

ModelBinders.Binders.Add(typeof(IdList), new IdListModelBinder());

这篇关于ASP .NET MVC 3基于Facebook的应用程序:分析查询字符串数组默认模型联编?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 21:07