【发布时间】:2015-09-28 11:44:05
【问题描述】:
下面是我的代码。
型号
public class ShiftsModel
{
public string UID { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public string Location { get; set; }
}
控制器
public class HomeController : Controller
{
public string xmlPath = HostingEnvironment.MapPath("~/App_Data/data.xml");
public ActionResult Index()
{
XDocument xml = XDocument.Load(xmlPath);
var shifts = (from b in xml.Descendants("Shift")
select new ShiftsModel
{
UID = (string)b.Attribute("UID"),
Date = (string)b.Element("Date"),
Time = (string)b.Element("Time"),
Location = (string)b.Element("Location")
}).ToList();
return View(shifts);
}
}
我现在想在我的 Index.cshtml 文件中引用它,如下所示:
@foreach(var shift in (List<object>ViewBag.shifts)) {
<tr>
<td>
<input type="text" id="date" name="date" placeholder="Date" value="@(ViewBag.date)" }>
</td>
<td>
<input type="text" id="time" name="time" placeholder="Shift time" value="@(ViewBag.time)" }>
</td>
<td>
<input type="text" id="location" name="location" placeholder="Location" value="@(ViewBag.location)" }>
</td>
</tr>
}
但是,我在List<object>ViewBag.shifts 行收到错误消息:
表示一个强类型的对象列表,可以通过 索引。
请对我做错了什么有任何建议吗?谢谢你:)
【问题讨论】:
-
根据您提供的代码,
shifts是模型,不在 viewbag 中。你在寻找@foreach(var shift in model) 吗? -
您尚未向
ViewBag添加任何内容。将@model List<ShiftsModel>添加到视图并使用for(int i = 0; i < Model.Count; i++) { @Html.TextBoxFor(m => m[i].Date ..... }访问项目 -
我猜,这只是一个错字,将
(List<object>ViewBag.shifts)更改为(List<object>)Model.shifts。如果您的视图没有任何模型,则添加适当的强类型模型(最好)或将其声明为@model dynamic(更差)或(更好)@model List<ShiftModel>使用foreach (var shift in Model)访问 -
@Nick 看最后一部分,你还需要改变你的 foreach。
-
@Nick 别担心!看看你已经得到的答案,它们显示了一个完整的工作示例!
标签: c# asp.net-mvc razor viewbag