我试图将HTML表格行中的选定模型直接传递给javascript函数,包括转换为JSON。由于以下问题,转换失败。另外,我吓坏了6个多小时,试图了解为什么它不起作用。现在,我知道是什么引起了问题,不知道如何解决。这是我尝试过的(简单易用):
<table class="table table-hover">
<thead align="center">
<tr>
<th scope="col">AssetID</th>
<th scope="col">Loaction</th>
<th scope="col">AreaIn</th>
<th scope="col">Rooms</th>
<th scope="col">ImageURL</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody align="center">
@foreach (var a in @Model.OwnAssetsList)
{
String[] assetArray = new String[8] { a.AssetID.ToString(), a.OwnerID.ToString(), a.OwnerPublicKey.ToString(), a.Loaction.ToString(), a.AreaIn.ToString(), a.Rooms.ToString(), a.ImageURL.ToString(), a.Price.ToString() };
<tr>
<td>@a.AssetID</td>
<td>@a.Loaction</td>
<td>@a.AreaIn</td>
<td>@a.Rooms</td>
<td><a target="_blank" [email protected]>Click</a></td>
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract(@a.Loaction/* or @a.ImageURL*/)">Offer Contract</button></td>
</tr>
}
</tbody>
使用Javascript:
@section scripts
{
<script type="text/javascript">
function offerContract(param)
{
document.getElementById("dialogAssetID").innerHTML = "Asset No:".bold()+param.AssetID;
document.getElementById("dialogOwnerAddress").innerHTML="Your Public Key:" +param.OwnerID;
}
</script>
}
[且仅当我传递@ a.Loaction或@ a.ImageURL时,javascript函数才会失败。这是控制台中的错误:“未捕获的SyntaxError:参数列表后缺少”。
模型的其余属性成功传递。我现在添加模型和表格方案:
public class Asset
{
[Key]
public int AssetID { get; set; }
[Required]
public int OwnerID { get; set; }
[Required]
public string OwnerPublicKey { get; set; }
[Required]
public string Loaction { get; set; }
[Required]
public int AreaIn { get; set; }
[Required]
public int Rooms { get; set; }
[Required]
public string ImageURL { get; set; }
[Required]
public double Price { get; set; }
}
我将不胜感激。在这个问题上花费了超过6个小时。
在您的Razor页面中,您基本上需要预先生成一个JavaScript对象,然后将其传递给JS:
在您的脚本部分中是个好地方:
@section scripts {
<script type="text/javascript">
var data = @Json.Serialize(@Model.OwnAssetsList);
function offerContract(index)
{
document.getElementById("dialogAssetID").innerHTML = "Asset No:".bold() + data[index].assetId;
document.getElementById("dialogOwnerAddress").innerHTML="Your Public Key:" + data[index].ownerId;
}
</script>
然后您的Razor可能看起来像这样(请注意,由于您选择使用foreach,因此没有直接的方法可以获取当前的迭代索引,因此我必须自我介绍:)]]
@{var i = 0} //
@foreach (var a in @Model.OwnAssetsList)
{
<tr>
...
<td><button class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="offerContract(@i)">Offer Contract</button></td>
</tr>
i += 1; // next iteration
}
}