我有一个很好的函数来获取我的 FormCollection(由控制器提供)。现在我想做一个模型绑定,并让我的模型绑定器调用该函数,它需要 FormCollection。由于某种原因,我可以找到它。我以为会是
controllerContext.HttpContext.Request.Form
问问题
4411 次
3 回答
15
试试这个:
var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form)
FormCollection 是我们添加到 ASP.NET MVC 中的一种类型,它有自己的 ModelBinder。您可以查看 FormCollectionBinderAttribute 的代码以了解我的意思。
于 2009-10-02T18:43:56.470 回答
1
直接访问表单集合似乎不受欢迎。以下是来自 MVC4 项目的示例,其中我有一个自定义 Razor 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);
}
}
于 2014-01-28T23:39:37.333 回答
0
使用 bindingContext.ValueProvider(和 bindingContext.ValueProvider.TryGetValue 等)直接获取值。
于 2009-10-02T18:47:38.940 回答