Tag Archives: inheritance

ASP.NET MVC with models inheritance and views

Hi

Recently I bumped into a intersing question on stackoverflow.com. The problem was that user had a view but wanted to have some input elements based on variable model. I mean if model passed to view is a, render a Email text input and if it is b then render Name text input. But in mvc you can pass only one model to view. So I suggested have a base model and base view and by checking the type of model in view load the related view using partial as below:

 public ActionResult Base()
        {
            return View(new DerviedOne());
        }

 public class BaseModel
    {
        public int Id { get; set; }
    }

    public class DerviedOne : BaseModel
    {
        public string Email { get; set; }
    }

    public class DerviedTwo : BaseModel
    {
        public string Name { get; set; }
    }
 @using Models
@model Models.BaseModel

@{
    ViewBag.Title = "Base";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Base</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()


<div class="form-horizontal">

<h4>BaseModel</h4>

        <hr/>
        @Html.ValidationSummary(true, "", new {@class = "text-danger"})

<div class="form-group">

<div class="col-md-offset-2 col-md-10">
                @Html.TextBoxFor(x=>x.Id)
                <input type="submit" value="Create" class="btn btn-default"/>
            </div>

        </div>

    </div>


    if(Model is DerviedOne)
     {
         Html.RenderPartial("DerviedOneView", Model as DerviedOne);
     }

    if (Model is DerviedTwo)
    {
        Html.RenderPartial("DerviedTwoView", Model as DerviedTwo);
    }
}