I'm using custom editor templates for most of my forms, but while attempting to use them to render a custom object picker I've found no easy way to pass information about the containing context to the editor template.
Specifically, my main form renders an edit for a domain object, and the editor template needs to render an AJAX picker which contains a list of objects which are dependent on the ID of the domain object. I'm passing the ID using the additionalViewData
parameter currently, which I think is error prone and therefore quite ugly.
My form contains code similar to the following:
@Html.EditorFor(model => model.CategoryId, new { id = model.id })
The editor template contains code like the following:
@{
var domainObjectId = ViewData["id"] as int?;
}
I'm using a custom ModelMetadataProvider
to select the object picker editor template, and hope to use a similar technique to pass information about the containing model to the editor template, but that doesn't seem be possible.
So, my questions are:
ModelMetadataProvider
to pass information about the containing model to the editor template?additionalViewData
parameter?Thanks in advance!
You need to understand that EditorTemplates are designed to be type specific, not context specific. Some thought was given to this with the AdditionalViewData parameter, but that's the best you're going to get.
If you're concerned about type safety, use ViewBag instead, which is a type-safe dynamic wrapper around ViewData.
@{
var domainObjectId = ViewBag.Id;
}