我有一个很好的函数,把我的FormCollection(从控制器提供)。现在,我想要做一个模型绑定,而不是和有我的模型绑定来调用这个函数,它需要的FormCollection。出于某种原因,我可以找到它。我认为这将是 controllerContext.HttpContext.Request.Form

有帮助吗?

解决方案

尝试这种情况:

var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form)

的FormCollection是我们加入到ASP.NET MVC一个类型,其具有其自己的模型绑定器。你可以看一下代码为FormCollectionBinderAttribute到明白我的意思。

其他提示

访问的形式收集直接似乎不赞成。以下是一个MVC4项目中,我有一个自定义剃刀EditorTemplate捕获在单独的表单字段的日期和时间的例子。定制绑定检索个别字段的值并将它们组合成一个DateTime

public class DateTimeModelBinder : DefaultModelBinder
{
    private static readonly string DATE = "Date";
    private static readonly string TIME = "Time";
    private static readonly string DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm";
    public DateTimeModelBinder() { }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext == null) throw new ArgumentNullException("bindingContext");

        var provider = new FormValueProvider(controllerContext);
        var keys = provider.GetKeysFromPrefix(bindingContext.ModelName);
        if (keys.Count == 2 && keys.ContainsKey(DATE) && keys.ContainsKey(TIME))
        {
            var date = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, DATE)).AttemptedValue;
            var time = provider.GetValue(string.Format("{0}.{1}", bindingContext.ModelName, TIME)).AttemptedValue;
            if (!string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(time))
            {
                DateTime dt;
                if (DateTime.TryParseExact(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} {1}", date, time),
                                            DATE_TIME_FORMAT,
                                            System.Globalization.CultureInfo.CurrentCulture,
                                            System.Globalization.DateTimeStyles.AssumeLocal,
                                            out dt))
                    return dt;
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

使用bindingContext.ValueProvider(和bindingContext.ValueProvider.TryGetValue等)直接获得的值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top