3
votes

How to access Model property(Like @Html.EditorFor(x=>Model.Name)) in Razor view of IEnumerable Type without using Loops??I.e If a view is strongly typed to some Model holding Model as a LIST.
Eg.

@model IEnumerable<EFTest2.DAL.package_master>


Then is it possible to Display TestBoxFor or EditorFor (to create new Model) Html helper without using foreach Loop.???

2
You still would have to iterate through out all of the Collection, thus it's called "List".IamStalker
You could write your own extension method(for HTML) to spit out html only if you are using at many placesAnand

2 Answers

3
votes

When some model property is of type IEnumerable<SomeType> you would normally define an editor/display template (~/Views/Shared/EditorTemplates/SomeType.cshtml or ~/Views/Shared/DisplayTemplates/SomeType.cshtml). This template will be automatically rendered for each element of the collection so that you don't need to write loops:

@Html.EditorFor(x => x.SomeCollection)

and inside the template you will be able to access individual properties:

@model SomeType
@Html.EditorFor(x => x.Name)
...

Now, if you absolutely need to directly access some element inside a view which is strongly typed to IEnumerable<SomeType> you would better use some other collection type such as IList<SomeType> or SomeType[] as view model which will give you direct access to elements by index and you will be able to do this for example to access the 6th element of the collection:

@model IList<SomeType>
@Html.EditorFor(x => x[5].Name)
0
votes

So basically you are mentioning of type List etc.

If you want to add values to the list accepting input from user from form fields and then add to the existing list in model. the easiest but not so elegant way would be

suppose you have class "Person" and then List in your model. first create an instance of person that will have empty person instance , add it to list and then bind this last list item to your edit for.

@{
    Person contact = new Person(); //Empty person instance
    PersonList.Add(contact);
     } 

later on bind this to your induvidual fields

 @Html.TextBoxFor(m => m.PersonList[PersonList.Count - 1].PrimaryContacts.FirstName)

This works good for Validation on model properties as-well and also after every form submit, for next inclusion you just add the new person. but take care to write the remove peice of code if form is cancelled.