mmssaann
mmssaann

Reputation: 1507

Loop through the properties in a model in C# , mVC4

I have view, whose I will be rending it from html helper functions.

@using PartyBiz.Models.Objects
@model IEnumerable<Person>
@Html.PageStructureEntity(Model)

I wrote the below sample method to return content to view:

 public static MvcHtmlString PageStructureEntity(this HtmlHelper helper, Person m)
    {
        TagBuilder
              stdDiv = MvcUtils.GetStdDiv(); //Parent Site Part Version's container


        switch (m.FirstName.GetType().FullName)
        {
            case "System.String":
                TagBuilder input = MvcUtils.GetStdInput();
                input.Attributes.Add("value", m.FirstName);
                stdDiv.InnerHtml = input.ToString();
                break;

            default:
                return null;
        }
        return MvcHtmlString.Create(stdDiv.ToString());
    }

I have to loop through every model object in IEnumerable and every property in that model object, render the inputs or checkboxes or datetimes as per their type.

My problem is I am doing it in a pretty standard style. Is there any best approach for this to write the code better, something using generics or built helper functions?

Your suggestions helps a lot..

Upvotes: 1

Views: 468

Answers (1)

Longball27
Longball27

Reputation: 696

You could try using

@Html.EditorForModel()

This will render all the default editor templates for your models properties.

See this for more details

Upvotes: 2

Related Questions