ASP.Net访问函数内的模型参数

时间:2015-06-21 12:36:48

标签: c# asp.net-mvc

我有一个load data infile文件,我正在使用该模型:

.cshtml

模型包含参数@model IEnumerable<WebApplicationMVCTest.Models.Test> (以及其他参数)。我在创建表时访问此值:

Date

我的代码 @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.SiteID) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> ... 中有一个函数,我希望将NotTested值作为参数之一传递给函数:

item.Date

问题是双重的。 1)我知道Date在此视图中是模型的一部分,因此在调用函数时它出现<script> document.onload = NotTested("Site 001", item.Date); function NotTested(SiteId, TestDate) { ... } </script> ,但2 onloadmodel中不在上下文中代码部分。

我知道<script>不存在item,因为这对for循环来说只是暂时的。我刚刚使用onload作为占位符参数。

调用函数时如何访问它?

2 个答案:

答案 0 :(得分:1)

根据您的评论,您的收藏中的每个项目的属性Date都相同,因此您可以使用

将其分配给javascript变量
var date = JSON.parse('@Html.Raw(Json.Encode(Model[0].Date))');

或在控制器中,分配到ViewBag.Date = yourDate;和脚本

var date = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Date))');

然后您可以使用

调用该函数
<script>
  $(function() {
    var date = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Date))');
    NotTested("Site 001", date);
  });
</script>

答案 1 :(得分:0)

将css类分配给日期项,并使用jquery根据css类选择日期项,如下所示:

@Html.DisplayFor(modelItem => item.SiteID, new { htmlAttributes = new { @class = "mySiteIDClass" } })

@Html.DisplayFor(modelItem => item.Date, new { htmlAttributes = new { @class = "myDateClass" } })

<script>
         document.onload = NotTested($(".mySiteIDClass"), $(".myDateClass"));

         function NotTested(SiteIds, TestDates) { //loop through date items }
</script>