【问题标题】:Displaying one object value (from a collection) in a label在标签中显示一个对象值(来自集合)
【发布时间】:2013-08-01 12:19:21
【问题描述】:

我正在学习 MVC4。我可以使用foreach 以表格格式显示记录。

现在,我需要在标签中显示(仅)第一个Topic 对象的Description。我需要在没有foreach 的情况下这样做。我们该怎么做?

查看

@model MvcSampleApplication.Models.LabelDisplay

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{


    foreach (var item in Model.Topics.Select((model, index) => new { index, model }))
    {
    <div>@(item.index) --- @item.model.Description---- @item.model.Code</div> <div></div>
    }
}

控制器动作

public ActionResult Index()
        {
            LabelDisplay model = new LabelDisplay();

            Topic t = new Topic();
            t.Description = "Computer";
            t.Code=101;

            Topic t3 = new Topic();
            t3.Description = "Electrical";
            t3.Code = 102;


            model.Topics = new List<Topic>();
            model.Topics.Add(t);
            model.Topics.Add(t3);

            return View(model);
        }

型号

namespace MvcSampleApplication.Models
{
    public class LabelDisplay
    {
        public List<Topic> Topics;
    }

    public class Topic
    {
        public string Description { get; set; }
        public int Code { get; set; }
    }
}

参考

  1. Iterate through collection and print Index and Item in Razor

【问题讨论】:

  • 不要在视图中执行 LINQ。为您的视图创建一个视图模型并在其中发送数据
  • @Shyju:在视图中执行 LINQ 查询(实际上会导致发出数据库查询)是错误的,但 LINQ 通常不一定在你看来是“错误的”。特别是,这里的 OP 遵循通用模式在 foreach 中获取索引值,这非常好。

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


【解决方案1】:

我需要在标签中显示(仅)第一个主题对象的描述

除非我完全误解了你,否则选择你视图中的第一个项目(仅)看起来像:

@if (Model.Topics.Any())
{
    @Html.DisplayFor(x => x.Topics.First().Description)
}

【讨论】:

  • 我有理由确定使用LabelFor 将无法正常工作——你会得到一个运行时错误。但是,OP 可以很容易地使用带有静态标签标签的Model.Topics.First().Description 位。
  • @ChrisPratt 哇,实际上……这有点尴尬,你看它不会抛出异常,但它实际上是在页面中添加了一个label 元素……是的,它是漫长的一天......
  • @Lijo LabelFor 助手将生成一个 html 元素 &lt;label for="Description"&gt;Description&lt;/label&gt; 而不仅仅是输出描述本身。也就是说,它具有接受文本内容作为参数的重载。但是,Html 标签元素通常用于具有相应文本框/输入的表单。不确定您是否属于这种情况。
  • @Lijo 恕我直言(我要做的就是使用@Html.DisplayFor,我已经编辑了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多