开发者

ASP.NET MVC Filters: How to set Viewdata for Dropdown based on action parameter

Im loading an entity 'Member' from its id i开发者_高级运维n route data.

[ListItemsForMembershipType(true)]
public ActionResult Edit(Member someMember) {...}

The attribute on the action loads the membership type list items for a dropdown box and sticks it in viewdata. This is fine for add forms, and search forms (it gets all active items) but I need the attribute to execute BASED ON THE VALUE someMember.MembershipTypeId, because its current value must always be present when loading the item (i.e. all active items, plus the one from the loaded record).

So the question is, what is the standard pattern for this? How can my attribute accept the value or should I be loading the viewdata for the drop down in a controller supertype or during model binding or something else?

It is in an attribute now because the code to set the viewdata would otherwise be duplicated in each usage in each action.


You can access the model object inside MVC filter OnActionExecuting:

public class ListItemsForMembershipType : ActionFilterAttribute
{
    // ...

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        Member model = filterContext.ActionParameters["someMember"] as Member
        // do your stuff, insert data into ViewData            
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜