开发者

Can I get to the containing Model of a property in an MVC2 Html Helper

I have an Html helper with the following signature:

public static MvcHtmlString UiAutoCompleteForWithId<TModel, TProperty>(this htmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)

I understand开发者_JAVA百科 how to get my hands on the value of the passed in member and it's metadata, but is there anyway to access the containing Model, or more specifically the value of a particular sibling member (a property) of the passed in member by name?

Cheers, Matthew

Edit: OK I think I can do this using the ModelMetadata.FromStringExpression method (sometimes it takes asking before you see it eh?), but I is this the best way to go about this?


If you need to access the value of a sibling member it means that you assume that the view model has this sibling member. This means that your html helper no longer needs to be generic. You could do this:

public static MvcHtmlString UiAutoCompleteForWithId<TProperty>(
    this HtmlHelper<MyViewModel> helper, 
    Expression<Func<MyViewModel, TProperty>> expression, 
    object htmlAttributes
)
{
    MyViewModel model = helper.ViewData.Model;
    var value = model.SomeOtherSiblingProperty;
    // TODO: do something with this property
    ...
}

Or if your view models implement some common base interface that contains the sibling member in question you could specify a generic constraint:

public static MvcHtmlString UiAutoCompleteForWithId<TModel, TProperty>(
    this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TProperty>> expression, 
    object htmlAttributes
) where TModel: ISomeInterface
{
    ISomeInterface model = helper.ViewData.Model;
    var value = model.SomeOtherSiblingProperty;
    // TODO: do something with this property
    ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜