view model 如下:
public partial class AViewModel
{
[DisplayName("查詢日期")]
public string QUERY_DATE { get; set; }
public List<Header> HeaderInfo { get; set; }
}
public partial class Header
{
public string Order { get; set; }
public int Qty { get; set; }
public Datetime Date { get; set; }
public string PartNo { get; set; }
}
controller如下:
public ActionResult QueryInfo(AViewModel vm)
{
string qDate = vm.QUERY_DATE;
vm.HeaderList = db.QueryHeaderList(qDate);
return View(vm);
}
public ActionResult QueryInfo()
{
var vm = new AViewModel();
string qDate = DateTime.Today.ToString("yyyyMMdd");
vm.QUERY_DATE = qDate;
vm.HeaderList = db.QueryHeaderList(qDate);
return View();
}
view 如下:
@using (Html.BeginForm("QueryInfo", "QueryInfo", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { })
<table style="width:100%; border-spacing:0;">
<tr>
<th class="header">@Html.LabelFor(model => model.QUERY_DATE)</th>
<td>
@Html.TextBoxFor(model => model.QUERY_DATE)
@Html.ValidationMessageFor(vm => vm.QUERY_DATE, "", new { })
</td>
<th class="header"> </th>
<td> </td>
</tr>
<tr>
<td colspan="4" align="right"><input type="submit"></td>
</tr>
</table>
<table style="width:95%; border-spacing:1;">
@foreach (var item in Model.HeaderList)
{
<tr>
<td>@Html.LabelFor(model => item.Order)</td>
<td>@Html.LabelFor(model => item.Qty)</td>
<td>@Html.LabelFor(model => item.PartNo)</td>
</tr>
}
<tr><td>=================================</td></tr>
@for (int i = 0; i < Model.HeaderList.Count; i++)
{
<tr>
<td>@Html.LabelFor(m => m.HeaderList[i].Order)</td>
<td>@Html.LabelFor(m => m.HeaderList[i].Qty)</td>
<td>@Html.LabelFor(m => m.HeaderList[i].PartNo)</td>
</tr>
}
</table>
}
為什無法顯示數據? 都是顯示 Order 、 Qty、 PartNo
請問是哪個地方設定錯誤?
1.把Html.LabelFor
當成屬性值,它實際是輸出屬性名稱(or DisPlayName)。
所以才都顯示Order、QTY、PartNO
2.表頭不需要foreach
3.表身用foreach + 使用item.屬性名稱
就可以抓取值
C# Online Compiler | .NET Fiddle
@model HelloWorldMvcApp.AViewModel
@{
Layout = null;
}
@using (Html.BeginForm("QueryInfo", "QueryInfo", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { })
<table style="width:100%; border-spacing:0;">
<tr>
<th class="header">@Html.LabelFor(model => model.QUERY_DATE)</th>
<td>
@Html.TextBoxFor(model => model.QUERY_DATE)
@Html.ValidationMessageFor(vm => vm.QUERY_DATE, "", new { })
</td>
<th class="header"> </th>
<td> </td>
</tr>
<tr>
<td colspan="4" align="right"><input type="submit"></td>
</tr>
</table>
<table style="width:95%; border-spacing:1;">
<tr>
<th>Order</th>
<th>Qty</th>
<th>PartNo</th>
</tr>
<tr><td><hr></td><td><hr></td><td><hr></td></tr>
@foreach(var item in Model.HeaderList){
<tr>
<td>@item.Order</td>
<td>@item.Qty</td>
<td>@item.PartNo</td>
</tr>
}
</table>
}