Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC2 - How to obtain parent model (container) inside template

I'm writing an MVC2 app using DataAnnotations. I have a following Model:

public class FooModel 
{
    [ScaffoldColumn("false")]
    public long FooId { get; set; }

    [UIHint("BarTemplate")]
    public DateTime? Bar { get; set;}
}

I want to create a custom display template for Bar. I have created following template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>

<div class="display-label">
    <span><%: Html.LabelForModel() %></span>
</div>
<div class="display-field">
    <span><%: Html.DisplayForModel()%></span>
    <%: Html.ActionLink("Some link", "Action", new { id = ??FooId?? }) %>
</div>

Now, my problem is that inside template for Bar I want to access another property from my model. I don't want to create a separate template for FooModel because than I will have to hardcode all other FooModel properties.

After a brief investigation with a debugger I can see that:

  1. this.ViewData.ModelMetadata.ContainerType is FooModel (as expected)
  2. this.ViewData.TemplateInfo has a non-public property VisitedObjects (of type System.Collections.Generic.HashSet<object>) which contains two elements: FooModel and DateTime?.

How can I get access to my FooModel? I don't want to hack my way around using Reflection.

Update:

I've accepted mootinator's answer as it looks to me as the best solution that allows type-safety. I've also upvoted Tx3's answer, as mootinator's answer builds upon it. Nevertheless, I think that there should be a better support form MVC in those kind of scenarios, which I believe are quite common in real world but missing from sample apps.

like image 408
Jakub Konecki Avatar asked Oct 24 '10 16:10

Jakub Konecki


2 Answers

Maybe you could create new class, let's say UserDateTime and it would contain nullable DateTime and rest of the information you need. Then you would use custom display template for UserDateTime and get access to information you require.

I realize that you might be looking for other kind of solution.

like image 50
Tx3 Avatar answered Sep 28 '22 09:09

Tx3


I think you may be better off extracting this functionality to an HtmlHelper call from the Parent View.

Something like RenderSpecialDateTime<TModel>(this HtmlHelper html, Expression<Func<TModel,DateTime?>> getPropertyExpression) would probably do the job.

Otherwise, you will have to do something like what Tx3 suggested. I upvoted his answer, but posted this as an alternative.

like image 45
smartcaveman Avatar answered Sep 28 '22 08:09

smartcaveman