Search code examples
c#asp.net-mvcasp.net-mvc-views

can i have dynamic model for mvc view


I am developing a Create form in a .Net MVC project. I will create a simple demo for the question as close as i can have for my real business scenario.

I have a person class and few other classes which inherited from it.

public class Person
{
    public int Id { get; set; }
    [Required]
    public string Forename { get; set; }
    [Required]
    public string Surname { get; set; }
    [Required]
    public DateTime Dob { get; set; }
}

public class Teacher: Person
{
    [Required]
    public string Department { get; set; }
}

public class Student: Person
{
    [Required]
    public string TermAddress { get; set; }
}

If i have a Action method for create as below.

public class PersonController : Controller
{
public ActionResult Create()
    {
        var personFactory = new PersonFactory();
        var p = personFactory.CreatePerson("student");
        return View(p);
    }
}
public class PersonFactory
{
    public object CreatePerson(string type)
    {
        switch(type)
        {
            case "teacher":
                return new Teacher();
                break;
            case "student":
                return new Student();
                break;
            default:
                return null;
                    break;

        }
    }            
}

Is it possible to have a view that can handle both cases? In my business case, there are 10+ different types of similar classes and i am wondering if there is a way that i can get around the problem without creating 10+ views. I know i have be strongly typed the view but it's fine. I can have 10+ view models as long as i can use a single view for that. Any alternative suggestions or ways i can get around this kind of problem are welcome. Thanks.

@{
    ????????????? just an idea .. something like that .. ???????????
    var type = "student";
    if(type == "stuent")
    {
        @model WebApplication1.Models.Student
    }
    else if(type == "teacher")
    {
        @model WebApplication1.Models.Teacher
    }
}

<h2>Create</h2>

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

<div class="form-horizontal">        

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

    @Html.EditorForModel()

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Solution

  • Unfortunately only one @model declaration is allowed in the file, so the logic you are trying to implement is not supported. If you are using just @Html.EditorForModel(), you can use @model WebApplication1.Models.Person and you will get the correct editor form generated.