Note that there are some explanatory texts on larger screens.

plurals
  1. PODerive Model from Another Model
    text
    copied!<p>In my ASP.Net MVC 3 project, I'd like to have a base class model object that has certain properties that I will then use in all of the other models in my application (or at least most of them). That way, the views that use these derived models will also have the base class model properties. </p> <p>The base class model properties could be set in, say a base class controller, and then somehow I need to populate the derived models with that same data. Any suggestions on how to best get 'er done?</p> <p>Or should I be looking into creating my own DefaultModelBinder somehow? I'm a little confused as to my options here. As if you couldn't tell. :)</p> <p><strong>Sample Code</strong></p> <p><em>Base Model</em></p> <pre><code>public class ElkModel { public bool IsAdministrator { get; set; } } </code></pre> <p><em>Derived Model</em></p> <pre><code>public class UserModel : ElkModel { [HiddenInput] public int User_ID { get; set; } // Other properties specific to this model } </code></pre> <p><em>So in the base controller</em></p> <pre><code>private BaseModel baseModel; protected override void OnActionExecuting(ActionExecutingContext filterContext) { baseModel = new baseModel(); baseModel.MyProperty = "test"; base.OnActionExecuting(filterContext); } </code></pre> <p><em>And in the derived controller action method</em></p> <pre><code>public ActionResult Index() { // Derives from the base model in the base controller UserModel model = new UserModel(); // model.IsAdministrator where IsAdministrator is a property of the base Model not UserModel return View(model); } </code></pre>
 

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