How to use UIHint attribute for interface property type?

I have the following presentation model:

public class PickUpLocationViewModel { public DateTime PuDate {get;set} public IAddressViewModel {get;set;} } 

Depends on the implementation of IAddressViewModel. I want to use the corresponding UIHint (“Airport”), UIHint (“Sea Port”), etc. Is it possible? If so, how?

+7
source share
2 answers

You can create an additional property in the IAddressViewModel of the template name, for example:

 public interface IAddressViewModel { string TemplateName { get; } } 

So, for each class that implements IAddressViewModel, you can define a separate template name, for example:

 public class SeaportAddressViewModel : IAddressViewModel { public string TemplateName { get { return "Seaport"; } } } 

Then, in your opinion, you can use one of EditorFor overloads, for example:

 @Html.EditorFor(m => m.Address, Model.Address.TemplateName) 

This should force him to use an editor template called Seaport.cshtml.

+1
source

Suppose you have the following models:

 public class PickUpLocationViewModel { public DateTime PuDate { get; set } public IAddressViewModel Address { get; set; } } public class AirportAddressViewModel: IAddressViewModel { public string Terminal { get; set; } } public class SeaportAddressViewModel: IAddressViewModel { public int DockNumber { get; set; } } 

and then the action of the controller:

 public ActionResult Index() { var model = new PickUpLocationViewModel { Address = new AirportAddressViewModel { Terminal = "North" } }; return View(model); } 

and corresponding presentation:

 @model PickUpLocationViewModel @Html.DisplayFor(x => x.Address) 

Now you can define the appropriate display / editor templates:

~/Views/Shared/EditorTemplates/AirportAddressViewModel.cshtml :

 @model AirportAddressViewModel @Html.DisplayFor(x => x.Terminal) 

~/Views/Shared/EditorTemplates/SeaportAddressViewModel.cshtml :

 @model SeaportAddressViewModel @Html.DisplayFor(x => x.DockNumber) 

Now, based on a specific type, ASP.NET MVC automatically uses the correct template.

And when it comes to snapping, you'll need a custom connectivity device. I have illustrated this here: https://stackoverflow.com/a/318969/

+1
source

All Articles