在到达操作之前,在OnActionExecuting中向模型添加内容

9

我有以下内容:

 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();
    }

现在我可以看到模型中的用户和方案正在被填充。

但是当我到达操作时,它们都是null?

我在这里做错了什么?

另外,这是否是向模型添加内容的正确方式?

以下是控制器代码:

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

}

你能否也发布一下你的“控制器”代码?你确定已经将“属性”添加到了“类”定义或适用的“操作”中吗? - Alex
添加了操作代码 - 你是说这应该可以工作?... - user156888
相同的问题在这里讨论:http://stackoverflow.com/questions/4766156/all-viewmodels-inherit-from-baseviewmodel-can-i-set-this-up-in-onactionexecut - Andrei Schneider
2个回答

7

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

如果出于某些原因您不想使用自定义模型绑定程序(这是在 asp.net-mvc 中填充操作参数的标准和推荐方式),则可以使用 ActionExecutingContext.ActionParameters 属性

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

1
我真的很不想承认,但为了其他人不犯同样的错误:我最初也使用了这种方法,但当我将属性添加到另一个操作时,它停止工作了。原因是什么?我在此操作中将我的模型命名为“input”!现在,如果属性被添加到具有错误命名模型的操作中,我会进行检查并抛出异常 :) - user156888
@iwayneo 为什么不使用自定义模型绑定器? - archil

1

回复有些晚了,但对其他人可能仍有用。我们可以通过稍微修饰我们的属性来在 OnActionExecuting 中获取 model 的值。

这是我们的过滤器类:

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)
    {
    }

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接