2013-04-09 56 views
0

我希望能够使用Html.ActionLink()将以下代码中的每个项目的id传递给jQuery函数。从Html.ActionLink传递模型项目id到jquery函数

@foreach (var item in Model) 
    { 
     if (item.AppointmentStatus == "P") 
     { 
     <div class="appointment-main-block" role="menuitem" tabindex="20"> 
      <div class="appointment-heading"> 
       @Html.DisplayFor(modelItem => item.Speciality) 
      </div> 
      <div class="appointmenttitle"> 
       Date 
       <br /> 
       <br /> 
       Clinician 
       <br /> 
       <br /> 
       Location 
      </div> 
      <div class="appointmentdata"> 
       @Html.DisplayFor(modelItem => item.AppointmentDate) 
       <br /> 
       <br /> 
       @Html.DisplayFor(modelItem => item.ClinicianName) 
       <br /> 
       <br /> 
       @Html.DisplayFor(modelItem => item.Location) 
      </div> 

      <div class="appointmentbutton appointmentbuttonclickable"> 
       View @Html.ActionLink(" ", "Details", "MyAppointments", new { id = item.AppointmentIdentifier.id }, new { onclick = "getAppointmentRef(item.AppointmentIdentifier.id)" }) 
       <br /> 
       <img src="/Content/images/icons/view.png" alt="view icon" /> 
      </div> 
     </div> 
     } 
    } 

// jQuery - Very Basic for now also considered 
$(".appointmentbutton").click(getAppointmentRef); 
    function getAppointmentRef(id) { 
       alert(id); 
      } 

的函数被调用确定,但即使我通过“你好”这似乎传递一个JSON字符串没有的,其PARAMS是“身份证” I,E。 123456789

如何让动作链接选取该模型项目的ID?

回答

3

首先你有一个语法错误。这一点,我认为,应改为:

onclick = "getAppointmentRef(@item.AppointmentIdentifier.id)" 

或者

onclick = "getAppointmentRef(" + @item.AppointmentIdentifier.id + ")" 

两者之一。

然而,主要是我会采取不同的方法:

@Html.ActionLink("Link text", "Details", "MyAppointments", new { id = item.AppointmentIdentifier.id }, new { @class = "myLink", data_id = item.AppointmentIdentifier.id }) 

然后在jQuery的:

$(".myLink").click(function() { 
    alert($(this).data("id")); 
}); 

这样的话,你必须关注更清晰的分离。

我希望这会有所帮助。

+0

似乎多余的使用Razor来制作一个ActionLink然后触发一个jQuery点击函数。我要么使用jQuery事件处理程序创建输入元素,要么一起去除jQuery函数,因为如果您只是更改页面,那么它并不是必需的 – 2013-04-09 16:44:14

+1

我同意。不过,我只是简单地教育了ConfusedShark,以便将jQuery和Model值与最佳实践原则混合在一起。我相信这不会是他们最终的代码,因为目前它没有多大意义。 – 2013-04-09 16:47:29

+1

我也使用'$(this).data(“id”)' – Lars 2013-04-09 16:48:00

0

为了您的按钮,你可以使用类似 -

<input type="button" data-apptid="@item.AppointmentIdentifier.id" class="myLink" value="Click me!" /> 

和你的jQuery也能像白鲸提到 -

$(".myLink").click(function() { 
    document.location.href = "/MyAppointments/Details/" & $(this).data("apptid"); 
}); 

这样,如果你需要做一些jQuery中,除了刚刚加载新页面,你可以在那里做,并有功能决定你是否重定向。

相关问题