OnActionExecuting在开始行动之前添加到模型

时间:2012-02-09 17:01:56

标签: c# asp.net-mvc-3 modelbinders action-filter

我有以下内容:

 public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        var model = filterContext.Controller.ViewData.Model as BaseViewModel;

        if (model == null)
        {
            model = new BaseViewModel();
            filterContext.Controller.ViewData.Model = model;
        }

        model.User = (UserPrincipal)filterContext.HttpContext.User;
        model.Scheme = GetScheme();
    }

现在逐步完成我可以看到模型上的用户和方案正在填充。

当我开始行动时,它们都是空的?

我在这里做错了什么?

除此之外,这是添加到模型的正确方法吗?

这是控制器代码:

[InjectStandardReportInputModel]
public ActionResult Header(BaseViewModel model)
{
    //by this point model.Scheme is null!!

}

2 个答案:

答案 0 :(得分:7)

Controller.ViewData.Model未在asp.net mvc中填充操作参数。该属性用于将数据从操作传递到视图。

如果由于某种原因你不想使用自定义Model Binder(这是在asp.net-mvc中填充动作参数的标准的,推荐的方式),你可以ActionExecutingContext.ActionParameters Property

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.ActionParameters["model"] = new BaseViewModel();
        // etc
    }

答案 1 :(得分:1)

回复迟到但对其他人有用。我们可以通过稍微装饰我们的属性来获取OnActionExecuting中模型的值。

这是我们的过滤器类

public sealed class TEST: ActionFilterAttribute
{

   /// <summary>
    /// Model variable getting passed into action method
    /// </summary>
    public string ModelName { get; set; }

    /// <summary>
    /// Empty Contructor
    /// </summary>
    public TEST()
    {
    }

    /// <summary>
    /// This is to get the model value by variable name passsed in Action method
    /// </summary>
    /// <param name="modelName">Model variable getting passed into action method</param>
    public TEST(string modelName)
    {
        this.ModelName = modelName;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var result = filterContext.ActionParameters.SingleOrDefault(ap => ap.Key.ToLower() == ModelName.ToString()).Value;
    }

}

    THIS IS OUR ACTION METHOD PLEASE NOTE model variable has to be same
    [HttpPost]
    [TEST(ModelName = "model")]
    public ActionResult TESTACTION(TESTMODEL model)
    {
    }

这就是.....如果你喜欢这个答案,请投票

相关问题