Anonim
Anonim

Reputation: 61

Custom Razor ForEach View

i have some issue for view in cshtml page.. i already define foreach like this

<table>
<tr>
<th>Type</th>
<th>Name</th>
</tr>
@foreach (var item in Model)
 {
<tr>
       <td>  @Html.DisplayFor(modelItem => item.typeBook)</td>
       <td>  @Html.DisplayFor(modelItem => item.bookName)</td>
<tr>    
 } 
</table>

and the view

     Type | Name
   Horror | Scary
   Horror | Spooky
    Jokes | Bean

but i want the view like this..

  Type | Name
Horror | Scary , Spooky
 Jokes | Bean

this my view model

public class BookViewModel 
    {


        [DataMember]
        public int IdBook { get; set; }

        [DataMember]
        [DisplayName("type Book")]
        public string typeBook { get; set; }

        [DataMember]
        [DisplayName("book Name")]
        [Required]
        public string bookName { get; set; }


    }

for select to database i use linq Exp

Expression<Func<Book, bool>> criteria = c => c.IdBook == (int)IdBook ; 
IOrderedEnumerable<BookViewModel> result = this.GetList(criteria).OrderBy(o => o.typeBook);
return result.ToList<BookViewModel>();

can anyone have idea for this?? any reference,sugestion will help.. Thanks !

Upvotes: 1

Views: 187

Answers (2)

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

Instead of customizing or writing any logic in razor view, You should pass custom ViewModel to your view. And you can use GroupBy query to create custom ViewModel field from your list. View should contain only render syntax.

Inside your controller update your method with following code :

// books is your original model data
var bookListViewModel = books.GroupBy(b => b.typeBook)
                                .Select(b => new BookViewModel()
                                {
                                    type = b.Key, 
                                    name = string.Join(",", b.Select(book => book.bookName))
                                });

So now you would have in BookViewModel, typeBook = "Horror" and bookName = "Scary , Spooky" as you need to display.

So in your view you can use it same as you are using. Just you have to pass ViewModel to your view now.

Upvotes: 1

MSTdev
MSTdev

Reputation: 4635

You have to implement your query as group by Type when you assign model in controller

e.g.

    var query = BookViewModel.
                Orderby(x =>x.bookName).
                GroupBy(x =>x.Type);

further query for three fields

 var query = BookViewModel.
                Orderby(x =>x.bookName).
                GroupBy(x =>x.Type,  n => n.Writer);

Upvotes: 0

Related Questions