20

How do I pass some additional properties to an EditorTemplate?

I want to use it like this (kind of pseudo code):

@Html.EditorFor(m => m.ReturnFlight, new { additionalViewData = new { FlightType = FlightType.Return } })
@Html.EditorFor(m => m.OutboundFlight, new { additionalViewData = new { FlightType = FlightType.Outbound } })

FlightTemplate:

<h1>FLight @Model.FlightNumber</h1>
@if(FlightType == FlightType.Outbound)
{
    // Display stuff for outbound flights
}
else if(FlightType == FlightType.Return)
{
    // Display stuff for return flights
}
@Form.TextboxFor(m => m.Destination)

1 Answer 1

32

You pretty much have it already - you can pass additional view data in exactly this way, using this overload. You just need to use it in your editor template. Remember values in the ViewData dictionary are also available in the dynamic ViewBag object.

@Html.EditorFor(m => m.ReturnFlight, new { FlightType = FlightType.Return })
@Html.EditorFor(m => m.OutboundFlight, new { FlightType = FlightType.Outbound })

FlightTemplate

<h1>Flight @Model.FlightNumber</h1>
@if(ViewBag.FlightType == FlightType.Outbound)
{
    // Display stuff for outbound flights
}
else if(ViewBag.FlightType == FlightType.Return)
{
    // Display stuff for return flights
}
@Form.TextboxFor(m => m.Destination)
3
  • Thanks for your fast and great answer, missed the ViewBag part and it's working now. Commented Jan 13, 2015 at 15:16
  • Nice, but how to do it for tag helpers? <editor asp-for="MyTrip.ReturnFlight" />
    – Vitaliy
    Commented Feb 27, 2023 at 14:27
  • TagHelpers work completely differently to HTML helpers, but to answer the question, you pass your data as attributes. You can create equivalent properties in your TagHelper to help coding and creating a strongly-typed mapping but unspecified attributes are serialized and available as strings ,e.g. <MyTag [email protected] custom-value="test" />
    – Rhumborl
    Commented Feb 2 at 15:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.