Sanjay Maharjan
Sanjay Maharjan

Reputation: 671

populating list in view using editorTemplates

here is my model

namespace chPayroll.Models.CustInformations
{
    public class CustContact
    {
        public int cId { get; set; }
        public int cNoType { get; set; }
        public string cNo1 { get; set; }
        public string cNo2 { get; set; }
        public string cNo3 { get; set; }
        public List<CustContact> contact { get; set; }
    }
}

here is my editorTemplates

@model chPayroll.Models.CustInformations.CustContact         


@Html.TextBoxFor(model => model.cNo1)
@Html.TextBoxFor(model => model.cNo2)
@Html.TextBoxFor(model => model.cNo3)

I need to show three textbox for taking email,three text box for taking telephone no. in view. how can I add the items to the list contact defined in the model so that it shows like this

email:--textbox1----textbox2----textbox3--
telephone:--textbox1----textbox2----textbox3--

and sends value to the controller

actually I am trying to send my data in list named contact here ie inside list at

index 0-email1-email2-email3
index 1-tel1-tel2-tel3

Upvotes: 2

Views: 118

Answers (2)

Display Name
Display Name

Reputation: 4732

@Sanjay: you have a strange construct in your view model:

public class CustContact
{
   public List<CustContact> contact;
}

Even if it compiles and machine understands it, I wouldn't use it as it is - you trying to lift yourself from the ground by pulling your hair up :)

It should be defined something along these lines (following your naming conventions & logic):

public class CustContact // single
{
    public int cId { get; set; }
    public int cNoType { get; set; }
    public string cNo1 { get; set; } // those are actual phones, emails etc data
    public string cNo2 { get; set; }
    public string cNo3 { get; set; }
}

public class CustContacts // plural
{
   public List<CustContact> Contacts;
}

View:

@model CustContacts
@EditorFor(m => Model)

Editor template:

@model CustContact
@Html.EditorFor(m => m.cNo1)
@Html.EditorFor(m => m.cNo2)
@Html.EditorFor(m => m.cNo3)

For brevity, we don't deal here with annotations, decorations, error handling etc.

Hope this helps.

Upvotes: 1

Suhas
Suhas

Reputation: 8478

Based on the comment on the question, I would build the models as below

public class CustContact
{
    public int cId { get; set; }
    public int cNoType { get; set; }
    public string cNo1 { get; set; }
    public string cNo2 { get; set; }
    public string cNo3 { get; set; }
}

public class Customer
{
    public CustContact Email {get; set;}
    public CustContact Telephone {get; set;}
}

then create an editor template for Customer and in that editor template have following logic

@Html.EditorFor(model => model.Email)
@Html.EditorFor(model => model.Telephone)

Hope this helps

Upvotes: 0

Related Questions