for 循环 - MVC 传递数据以查看和循环



我对MVC非常困惑。

我没有任何代码要显示,因为我不知道该怎么做。

我有一个对象

public class Name()
{
  String name="balh"
  String something="blah blah"
  //this object works fine and doesn't look like this it has the appropriate get;set;
  //use this as just an example
  //please disregard this format
} 

现在我有一个

List<Name> list;//this just holds all of my objects

我需要将它们传递到视图

我一直看到一些关于模型的东西,但我没有看到它在任何地方声明

如何在视图中循环创建类似的东西

<div> object1 string</div>
<div> object2 string</div>
<div> object3 string</div>
<div> object4 string</div>
<div> object5 string</div>

假设您使用列表作为模型,您的视图将如下所示:

@model List<Name>
@foreach(var item in Model) {
  <div> @item.name @item.something</div>
}

因此,您的控制器操作方法可能是:

public ViewResult Index() {
  // Somehow build list which is List<Name>
  return View(list);
}

编辑:你看起来很新,所以我建议尝试本教程:http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3

让我们举个例子。

型:

public class MyViewModel
{
    public string Name { get; set; }
    public string Something { get; set; }
}

控制器:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        List<MyViewModel> model = new List<MyViewModel>();
        model.Add(new MyViewModel { Name = "some name", Something = "something" });
        model.Add(new MyViewModel { Name = "some other name", Something = "something else" });
        return View(mdoel);
    }
}

查看 ( ~/Views/Home/Index.cshtml ):

@model IEnumerable<MyViewModel>
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Something</th>
        </tr>
    </thead>
    <tbody>
    @foreach (vat item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Something</td>
        </tr>
    }
    </tbody>
</table>

使用此代码

  @foreach (vat item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Something</td>
        </tr>
    }

最新更新