【问题标题】:How to split a value from database in view?如何在视图中从数据库中拆分值?
【发布时间】:2016-04-17 18:41:21
【问题描述】:

我有一张叫书的桌子:

 public partial class Book
{
    public Book()

    [Key]
    public int Book_id { get; set; }

    [Required]
    [Display(Name = "Title Name")]
    [StringLength(70,MinimumLength =3)]
    public string Book_name { get; set; }

    [Display(Name = "Edition")]
    [Range(1, 20)]
    public int Edition { get; set; }    


    [StringLength(50)]
    [Display(Name = "Author Name")]
    public string Author_name { get; set; }



}

在此表中,有一个名为 Author_Name 的属性。

Author_Name 通常我会在其中保存如下值:

Name1,Name2,Name3

在我看来,我试图将它的价值拆分为每个链接都建立一个特定的链接,但我没有做到这一点。这是我的视图代码:

@model SmartBookLibrary.ViewModel.BooksDetailsVm

@{
    ViewBag.Title = Model.Book.Book_name;

    var s = Model.Book.Author_name.ToString();
    string[] Auth= s.Split(',');
}
<div class="container">

    <div class="row">
                    <p itemprop="author"><i class="glyphicon glyphicon-pencil"></i> <b>Author Name :</b>
@foreach(var val in Auth){
<a style="color:#777777" href="~/Author/@Model.Book.Author_name">@Auth.ToString();</a>
}

</p><hr>         </div>                                                                              </div>

所以当我检查结果时,它没有打印任何内容或显示任何错误..如何解决这个问题,谢谢..

【问题讨论】:

  • 不要在视图中使用这样的代码,也不要使用实体模型作为视图模型。引入一个单独的视图模型来保存您要显示的属性。
  • 实际上,我仅在从混合表或多个表中收集数据时才使用 ViewModel ......但就从一张表或直接获取数据而言,我直接使用模型..这是一个问题还是什么?

标签: asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

试试这个方法:

@{
   //var s = Model.Book.Author_name.ToString(); 
    var s = "Nazmul,khadiza,nowrin";
    string[] Auth = s.Split(',');
}
<div class="container">

    <div class="row">
        <p itemprop="author">
            <i class="glyphicon glyphicon-pencil"></i> <b>Author Name :</b>

        @for (int i = 0; i < Auth.Length; i++)
        {
            <a style="color:#777777">@Auth[i];</a>
        }

        </p><hr>
    </div>
</div>

或者如果你在数组上调用 .ToString() 将返回 System.String[]so 如果你想显示数组中的每个值,试试这个:

 @foreach (string val in Auth)
            {
                <a style="color:#777777">@val;</a>
            }

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多