【发布时间】:2021-09-01 21:02:25
【问题描述】:
我有一个活跃/不活跃的交易列表,我希望在我的视图中显示一个包含活跃交易列表的数据表。每当我加载视图时,我都会收到无效的 JSON 响应。使用浏览器对请求进行故障排除我看到我的响应只是显示我的视图的 HTML。
我确信我遗漏了一些非常明显的东西。作为记录,在我的控制器操作中,我尝试返回一些不同的东西但无济于事(我将在下面列出)
我的控制器代码:
public ActionResult TFSA()
{
var trades = db.Trades.Where(t => t.AccountName == "TFSA" && t.Active == true).OrderBy(l => l.TradeID).ToList(); ;
TradeIndexViewModel model = new TradeIndexViewModel()
{
ActiveTrades = Mapper.Map<IEnumerable<Trade>, List<ActiveTradesViewModel>>(trades)
};
return View();
//return Json(new { data = model.ActiveTrades }, JsonRequestBehavior.AllowGet);
//return Json(model.ActiveTrades, JsonRequestBehavior.AllowGet);
//return View(jsonModel);
}
注释掉的返回值是我尝试过的。当我返回 JSON 时,我的应用程序只会显示 JSON 数据(无 HTML)。
我的视图模型:
public class TradeIndexViewModel
{
public IEnumerable<ActiveTradesViewModel> ActiveTrades { get; set; }
public IEnumerable<ClosedTradesViewModel> ClosedTrades { get; set; }
}
public class ActiveTradesViewModel
{
[Display(Name = "Stock")]
public string Ticker { get; set; }
[Display(Name = "Shares")]
public int Shares { get; set; }
[Display(Name = "Avg Cost")]
public float AvgCost { get; set; }
[Display(Name = "Book Value")]
public float BookValue { get; set; }
[Display(Name = "Price")]
public float Price { get; set; }
[Display(Name = "Market Value")]
public float MarketValue { get; set; }
[Display(Name = "Daily Profit")]
public float DailyProfit { get; set; }
[Display(Name = "Profit")]
public float Profit { get; set; }
[Display(Name = "ROI")]
public string ROI { get; set; }
[Display(Name = "Fees")]
public float Fees { get; set; }
}
我的观点:
@model InvestmentProject.ViewModels.TradeIndexViewModel
<html>
<body>
<div class="jumbotron jumbotron-flud">
<table id="tfsaActiveTrades" class="table table-striped table-hover display">
<thead>
<tr>
<th>Stock</th>
<th>Shares</th>
<th>Avg Cost</th>
<th>Book Value</th>
<th>Price</th>
<th>Market Value</th>
<th>Profit/Day</th>
<th>Profit</th>
<th>ROI</th>
<th>Fees</th>
</tr>
</thead>
</table>
</body>
</html>
@section Scripts{
<script type="text/javascript">
$('#tfsaActiveTrades').DataTable({
"ajax": {
"url": "/Home/TFSA",
"type": "GET",
"dataType": "json"
},
"columns": [
{
"data": "Ticker",
"autoWidth": true,
"searchable": true
},
{
"data": "Shares",
"autoWidth": true,
"searchable": true
},
{
"data": "AvgCost",
"autoWidth": true,
"searchable": true
},
{
"data": "BookValue",
"autoWidth": true,
"searchable": true
},
{
"data": "Price",
"autoWidth": true,
"searchable": true
},
{
"data": "MarketValue",
"autoWidth": true,
"searchable": true
},
{
"data": "DailyProfit",
"autoWidth": true,
"searchable": true
},
{
"data": "Profit",
"autoWidth": true,
"searchable": true
},
{
"data": "ROI",
"autoWidth": true,
"searchable": true
},
{
"data": "Fees",
"autoWidth": true,
"searchable": true
},
],
});
</script>
}
我也很高兴能以不同的方式显示我的 activetrades 视图模型中的内容。
【问题讨论】:
-
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。
标签: c# asp.net-mvc datatables