简体   繁体   English

自定义剃须刀每次查看

[英]Custom Razor ForEach View

i have some issue for view in cshtml page.. i already define foreach like this 我在cshtml页面中查看时遇到了一些问题。我已经像这样定义了foreach

<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 对于选择数据库,我使用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 ! 任何参考,建议都会有所帮助。

Instead of customizing or writing any logic in razor view, You should pass custom ViewModel to your view. 不应在剃刀视图中自定义或编写任何逻辑,而应将自定义ViewModel传递给视图。 And you can use GroupBy query to create custom ViewModel field from your list. 您可以使用GroupBy查询从列表中创建自定义ViewModel字段。 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. 因此,现在您需要在BookViewModel中显示typeBook =“ Horror”和bookName =“ Scary,Spooky”。

So in your view you can use it same as you are using. 因此,在您看来,您可以像使用它一样使用它。 Just you have to pass ViewModel to your view now. 只是您现在必须将ViewModel传递给您的视图。

You have to implement your query as group by Type when you assign model in controller 在控制器中分配模型时,必须group by Type将查询实现为group by Type

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM