0

Is there a way to use something like this: System.Web.Mvc.ViewUserControl<DateTime>? I get an exception that the type is a value type, not a reference type. What is the proper way to resolve this? Thanks.

Edit

What I am trying to accomplish is having a control that takes a DateTime to render a calendar. I want to pass in the DateTime from my ViewData using "dot notation" for MVC.

Edit 2

I heard/seen that some MvcContrib projects might have this capability, but I can't seem to find it again.

5
  • look, there are "dots" in my answer! Commented Mar 12, 2009 at 14:07
  • But I am tring to be Generic. I don't want it to depend on MyModel, just a DateTime. Commented Mar 12, 2009 at 15:02
  • Ok, if you want to keep strong typing, then putting DateTime as the ViewModel is not possible. Your only option is to name MyModel something like CalenderModel. That's still generic. It's okay for views to depend on View Model types, that's acceptable design Commented Mar 12, 2009 at 23:20
  • Also, you can make it not type-safe by not setting the TViewModel type on CalView:ViewUserControl and manually cast ViewData.Model to DateTime. Commented Mar 13, 2009 at 6:57
  • I'm confused. You don't want to take a dependency on a custom class (e.g. MyCalenderModel), but you're okay with taking a dependency on MvcContrib custom ViewUserControl? I wouldn't take a dep on MvcContrib for this. Commented Mar 14, 2009 at 6:14

1 Answer 1

4

There is no way to resolve this - only workarounds. You cannot include Value types as TModel in ViewUserControl as TModel has a constraint to be a reference type.

The easy workaround is to wrap your value type in a class as your model.

class MyModel {
  public DateTime? DateTime {get;set;}
}

By defining your own class like MyModel above, you can now pass a DateTime to your views, like so

ActionResult MyActionMethod() {
  var db = new MyDataContext();
  var dbThing = db.Things.Where(t=> t.DateTimeProperty>=DateTime.Now).First();
  return View("myView", new MyModel{DateTime = dbThing.DateTimeProperty});
}

Your view of course will need to define MyModel as it's model type, like so

public partial class MyView:ViewUserControl<MyModel> {
 //snip
}

And inside your View, simply refer to the DateTime property to access the DateTime.

<%=Model.DateTime%>
Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't compile or you don't want to wrap in a class?
Oky..that's not what I asked. Hopefully my update answers your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.