0

I have strongly typed IEnumerable of two records which I am passing to view from controller. I always have maximum two records. I need to print these two record in separate form i.e. HTML beginform.

My question is how I can print IEnumerable Model data without using @for or @foreach loop??? Can you use some kind of index to read object in model and its data based on index???

Get data from record

public List<EmergencyContact> GetEmergencyContactByStudentID(int _studentID)
    {
        try
        {
            using (var _uow = new StudentProfile_UnitOfWork())
            {
                var _record = (from _emergencyContact in _uow.EmergencyContact_Repository.GetAll()
                               join _student in _uow.Student_Repository.GetAll() on _emergencyContact.StudentID equals _student.StudentID
                               where _emergencyContact.StudentID == _studentID 
                               select _emergencyContact).ToList();

                return _record;
            }
        }
        catch { return null; }
    }

Controller

 public ActionResult EditEmergencyContact()
    {
       int _studentEntityID = 0;

        _studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());

        List<EmergencyContact> _emergencyContactModel = new List<EmergencyContact>();

        _emergencyContactModel = _studentProfileServices.GetEmergencyContactByStudentID(_stu


  return PartialView("EditEmergencyContact_Partial", _emergencyContactModel);

    }

View

@model IEnumerable<App.DAL.Model.EmergencyContact>
.............//other code

 @Html.EditorFor(modelItem => model.NameOfContact, new { htmlAttributes = new { @class = "form-control" } })

above line @html.editorFor give error; refer to screenshot as below

enter image description here

1 Answer 1

2

You can access it by it's Index if you use a List:

@model List<App.DAL.Model.EmergencyContact>
.............//other code

 @Html.EditorFor(modelItem => model[0].NameOfContact, new { htmlAttributes = new { @class = "form-control" } })

But since you are now accessing the object by it's index I would always recommend checking to see if it's null first, even know you say you will always have 2 items in the collection, it doesn't do any harm checking.

Update

You can check if it is null by doing the following in a Razer view:

@if(Model[0] != null) 
{
    @Html.EditorFor(modelItem => model[0].NameOfContact, new { htmlAttributes = new { @class = "form-control" } })
}
Sign up to request clarification or add additional context in comments.

1 Comment

I can ensure to check this on server-side i.e. controller but how can i check null reference in razor view?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.