Use Interface and implement it on two models, this is exactly what they are used for.
Here is an example of two different views using two different models that implement the interface. This is subtyping instead of ad-hoc polymorphism .
public class ViewModelOne : IReusableView { public string Name { get; set; } public string Something { get; set; } public int ANumber { get; set; } } public class ViewModelTwo : IReusableView { public string Name { get; set; } public string Thing { get; set; } public string SomethingElse { get; set; } public int ANumber2 { get; set; } } public interface IReusableView { string Name { get; } }
So, we have a really simple partial view: "InnerPartialView":
@model TestIntegration.Models.IReusableView <div> @Model.Name </div>
What is used in the home page and on the pages of this example controller:
public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(new ViewModelOne() { Name = "hello", Something="sdfsdfs", ANumber = 1 }); } public ActionResult About() { return View(new ViewModelTwo() { Name = "hello 2", SomethingElse = "aaaddd", ANumber2 = 10, Thing="rand" }); } }
Home view:
@model TestIntegration.Models.ViewModelOne @{ ViewBag.Title = "Home Page"; } <h2>@ViewBag.Message</h2> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. @Html.Partial("InnerPartialView") </p>
View View:
@model TestIntegration.Models.ViewModelTwo @{ ViewBag.Title = "About Us"; } <h2>About</h2> <p> Put content here. @Html.Partial("InnerPartialView") </p>
mattmanser
source share