使用@ Ajax.ActionLink

时间:2015-11-17 09:37:20

标签: jquery asp.net-mvc

目标:通过@Ajax.ActionLink()将userId和两个时间戳传递给控制器​​。 到目前为止我所拥有的:

<table class="table table-hover ALStable thickborder" id="resultsTable">
  <thead>
    <tr>
      <th>Username</th>
      <th>Access level</th>
    </tr>
  </thead>
  <tbody>
    @for (int i = 0; i < Model.Users.Count(); i++)
    {
      <tr>
        <td>
          @Ajax.ActionLink(Model.Users[i].Username, "UserTracking", new { userId = Model.Users[i].Id }, new AjaxOptions { UpdateTargetId = "userTracking" }, new { @style = "font-weight:bold;" })
        </td>
        <td>@Html.DisplayFor(m => m.Users[i].AccessDescription, new { htmlAttributes = new { @class = "form-control", @style = "width: 100%" } })</td>
      </tr>
    }
  </tbody>
</table>

<h3 class="text-primary shadowedtext">Time filter</h3>
<p>Show from:</p>
<div id="datetimepicker1"></div>

<script type="text/javascript">
  $(function () {
    $('#datetimepicker1').datetimepicker({
      inline: true,
      format: 'DD MMMM YYYY',
      defaultDate: moment().subtract(1, "days")
    }).on("dp.change", function (e) {
      setDate(e.date.valueOf(), 0);
    });
  });
</script>

@Html.HiddenFor(m => m.FromDate)

<p>Show until:</p>
<div id="datetimepicker2"></div>

<script type="text/javascript">
  $(function () {
    $('#datetimepicker2').datetimepicker({
      inline: true,
      format: 'DD MMMM YYYY',
      defaultDate: moment()
    }).on("dp.change", function (e) {
      setDate(e.date.valueOf(), 1);
    });
  });
</script>

@Html.HiddenFor(m => m.UntilDate)

<div id="userTracking"></div>

控制器方法

public ActionResult UserTracking(int userId, long from, long until)
{
  Models.GPSInformation detail = new Models.GPSInformation();
  .....
  return PartialView(detail);
}

页面上还有两个日期时间选择器,用户可以在其中选择日期间隔。为了测试,我用虚拟数据填充了from和until参数。
该部分在使用所选日期的时间戳填充id时得到解决,但是当单击actionlink时我无法传递这两个值。
任何想法,帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

使用jquery ajax方法更新DOM,而不是使用Ajax.ActionLink()

更改html以生成链接

@for (int i = 0; i < Model.Users.Count(); i++)
{
  <a href="#" class="details" data-userid="@Model.Users[i].Id">Model.Users[i].Username</a>
}

然后包含一个脚本来处理链接.click()事件,调用服务器并更新DOM。注意我在这里假设您要传递给控制器​​方法的其他值是2个隐藏输入的值(FromDateUntilDate

var url = '@Url.Action("UserTracking")';
var placeholder = $('#userTracking');
$('.details').click(function() {
  var userid = $(this).data('userid');
  var from = $('#FromDate').val();
  var until = $('#UntilDate').val();
  placeholder.load(url, { userId: userid, from: from, until: until });
});