Forza
Forza

Reputation: 1649

How to get a comma between items in the View?

In my View, I want to display Guest Id's seperated by a comma but I don't know how. Right now it looks like the image below. 16 and 17 are Id's from seperate guests. This is confusing.

enter image description here

My model looks like this:

public class Guest
{
    [Key]
    public int GuestId { get; set; }
    //Vreemde sleutel van Reservation
    public Int32? ReservationId { get; set; }
}

The controller generating the View looks like this:

public ActionResult Index()
    {
        return View(_reservationrepository.GetAllReservations());
    }

public IQueryable GetAllReservations()
    {
        return db.Reservations.Include(r => r.spot).Include(r => r.User).Include(r => r.Guests);

    }

My View displaying the Id's looks like this:

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Guests)
    </td>
</tr>
}

How can I make the guest Id's seperated by a comma?

Upvotes: 0

Views: 113

Answers (3)

Jonathan Kittell
Jonathan Kittell

Reputation: 7493

You can separate the list of <int> by comma like this.

// old way
List<int> list = ...;
string.Join(",", list.Select(n => n.ToString()).ToArray());

// new way - just pass in list, no need to call .ToArray()
var list = new List<int> { 1, 2, 3 };
string.Join(",", list);

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15923

You can include a comma by joining it with the result like

@string.Join(",", Model.Guests.Select(g => g.GuestId))

Upvotes: 2

David
David

Reputation: 218950

If your view has a collection of Guest objects (let's call it Model.Guests for now), then you can join the IDs into a delimited string:

@string.Join(",", Model.Guests.Select(g => g.GuestId))

Or, depending on the semantic context of the view model (if it's just for the view and not really a business model) then you might even put that on the model itself:

public string GuestIDs
{
    get
    {
        return string.Join(",", Guests.Select(g => g.GuestId));
    }
}

and just bind the view to that property:

@Model.GuestIDs

Upvotes: 2

Related Questions