【问题标题】:How to pass model data from view to partial view in loop in MVC如何在MVC中循环将模型数据从视图传递到部分视图
【发布时间】:2012-12-07 14:08:30
【问题描述】:

我有一个带有强类型模型视图的视图,我需要将这些数据循环传递给部分视图。 (部分视图有点像数据模板的角色)

型号:

公共类 Foo {

public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }

}

控制器:

public ActionResult Index()
    {
        var foo = new List<Foo>();

        for (var i = 1; i < 3; i++)
        {
            foo.Add(new Foo{Content = "test content " + i, Title = "test title " + i, Id = i});
        }
        return View(foo);
    }

查看(索引):

@model List<Project.Models.Foo>
 @foreach (var foo in Model)
    {
        Html.RenderPartial("OneFoo", foo);
    }

查看(OneFoo):

@using Project.Models
<div>
    Title:
        @Html.LabelFor(f => f.Title)
        Content:
        @Html.LabelFor(f => f.Content)
    }
</div>

我得到的输出是:Title: Title, Content: Content - 它没有得到实际值。

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    你使用了错误的助手,使用:

    @Html.DisplayFor(f => f.Content)
    

    @Model.Content
    

    【讨论】:

    • 太棒了 - 谢谢 - MVC“花式语法”仍然是新手。就这么简单:) 看起来。谢谢大家。
    【解决方案2】:
    @Html.LabelFor(f => f.Title)
    

    这正是它所说的,打印出标签。正如 Eric 所说,您需要使用 DisplayFor 来显示实际内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-26
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多