bibble235
bibble235

Reputation: 818

Render custom controls in mvc in C#

I have a need to display many different data types on an MVC page using C#.

What is the best way to code this up. I have 200 items with 10-15 different data types I want to be able to edit.

I could put all of the code in the cshtml but would prefer to, as I have with the original php code, call a function to render the controls.

if(controlType = "checkBox"
{
   ...
}
else if(controlType = "string"
{
   ...
}
else if(controlType = "myClassType"
}

Thanks

Upvotes: 0

Views: 179

Answers (2)

Jinto John
Jinto John

Reputation: 363

The EditorFor() helper displays a user interface for editing a model property. This user interface is known as Editor Template. Check the below example for more details,I have Index() action,,return a list of object with different datatypes

public ActionResult Index()
{
    NorthwindEntities db=new NorthwindEntities();
    Employee emp = db.Employees.Find(1);
    return View(emp);
} 

The preceding code retrieves an Employee from the database whose EmployeeID is 1. It then passes this Employee object to the Index view. The Index view contains the following markup:

@model Demo.Models.Employee

@{
    Layout = null;
}
...
<body>
    @using(Html.BeginForm())
    {
        @Html.DisplayFor(m=>m.EmployeeID)
        @Html.DisplayFor(m=>m.FirstName)
        @Html.DisplayFor(m=>m.BirthDate)
    }
</body>
</html>

It then uses the DisplayFor() helper to show three model properties EmployeeID, FirstName, and BirthDate.

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

Use Html.EditorFor. It will look for a matching template depending on the datatype of the property in the ViewModel in the Views\Shared\EditorTemplates folder.

For example, you can define a template Boolean.cshtml to render a checkbox for boolean values of your model.

See Using Display Templates and Editor Templates in ASP.NET MVC.

Upvotes: 1

Related Questions