Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an ASP.net MVC user control with unknown generic type parameter?
    primarykey
    data
    text
    <p>Currently I'm using a base class for some Customer model classes. As defined as follows</p> <pre><code>public abstract class BaseCustomerModel&lt;T&gt; where T : IUserEntity </code></pre> <p>For further clarification, the IUserEntity contains:</p> <pre><code>public interface IUserEntity { string ErrorMessage { get; } } </code></pre> <p>That property among some other things will be exposed in an ErrorTextControl.ascx:</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;(...).Models.BaseCustomerModel&lt;(...).IUserEntity&gt;&gt;" %&gt; &lt;tr&gt; &lt;td colspan="2"&gt;&lt;%: Html.DisplayFor(model =&gt; model.ErrorMessage) %&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I'll call the user control like so:</p> <pre><code>&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&lt;(...).Models.MyUserModel&gt;" %&gt; &lt;% if (Model.HasErrors) { Html.RenderPartial("ErrorTextControl", Model); } %&gt; </code></pre> <p>Last piece of code (MyUserEntity implements IUserEntity):</p> <pre><code>public class MyUserModel : BaseCustomerModel&lt;MyUserEntity&gt; </code></pre> <p>Unfortunately this obviously doesn't work, because the generic type can't be implicitly casted to an IUserEntity. Therefore resulting in the following error message in the browser:</p> <blockquote> <p>Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type '(...).Models.MyUserModel', but this dictionary requires a model item of type '(...).Models.BaseCustomerModel`1[(...).IUserEntity]'.</p> </blockquote> <p>So questions:</p> <ul> <li>Is there any way to define a user control with a generic base class from which the type is not yet known? If yes, how to accomplish such thing?</li> <li>If not, any workaround, common solution or ideas to be able to have a generic user control?</li> </ul> <p>Many thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload