gpt4 book ai didi

asp.net-mvc-4 - 如何为强类型 View 动态地将数组值添加到模型数据?

转载 作者:行者123 更新时间:2023-12-02 00:05:39 25 4
gpt4 key购买 nike

这里是编程环境。

  • 框架:ASP.NET Framework 4
  • 语言:Visual C# 2010
  • 设计模式:MVC 4
  • 查看引擎:Razor

这是场景。

我正在使用以下代码创建一个网页:

项目跟踪.cs

using System;

namespace MyProject.Models
{
public class ProjectTracking
{
public int ProjectID
{
get;
set;
}
public string ProjectName
{
get;
set;
}
public DateTime ProjectDate
{
get;
set;
}
}
}

ProjectTrackingController.cs

using ProjectTracking.Models;
using System;
using System.Web.Mvc;

namespsace MyProject.Controllers
{
public class ProjectTrackingController:Controller
{
public ActionResult Index()
{
ProjectTracking[] projects =
{
new ProjectTracking
{
ProjectID = 1,
ProjectName = "Project 1",
ProjectDate = DateTime.Now
},
new ProjectTracking
{
ProjectID = 2,
ProjectName = "Project 2",
ProjectDate = DateTime.Now.AddDays(1)
},
new ProjectTracking
{
ProjectID = 3,
ProjectName = "Project 3",
ProjectDate = DateTime.Now.AddDays(2)
}
};
}

public ActionResult New()
{
...omitted for brevity...
}
}
}

索引.cshtml

@using MyProject.Models
@model ProjectTracking[]
@{
ViewBag.Title = "Project Tracking";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<p>
@Html.ActionLink("Add a New Project", "New")
</p>
@if (Model.Length > 0)
{
<table>
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Date
</th>
</tr>
</thead>
<tbody>
@foreach (ProjectTracking p in Model
{
<tr>
<td>
@p.ProjectID
</td>
<td>
@p.ProjectName
</td>
<td>
@p.ProjectDate
</td>
</tr>
}
</tbody>
</table>
}
else
{
<h2>No project tracking data found.</h2>
}

到目前为止这似乎有效。这是我面临的挑战。我想将数组中的结果插入到 ProjectID 中。我需要做什么才能做到这一点?

例如,

        int[] projectInt = new int[3] { 1, 2, 3 };
public ActionResult Index()
{
ProjectTracking[] projects =
{
new ProjectTracking
{
ProjectID = projectInt???...

也许这是一种糟糕的方法,需要完全不同的策略?

最佳答案

    int[] projectInt = new int[3] { 1, 2, 3 };

List<ProjectTracking> projects = new List<ProjectTracking>();
foreach (var i in projectInt)
{
var project = new ProjectTracking{
ProjectID = projectInt[i],
...
}
projects.Add(project);
}

关于asp.net-mvc-4 - 如何为强类型 View 动态地将数组值添加到模型数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18500208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com