簡體   English   中英

從Html.ActionLink將模型項ID傳遞給jquery函數

[英]Pass model item id to jquery function from Html.ActionLink

我希望能夠使用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);
            }

該函數稱為ok,但是即使我傳遞了“ hello”,它似乎也傳遞了JSON字符串,其參數都不是“ id”。 123456789

如何使Actionlink拾取該模型項目的ID?

首先,您在這里存在語法錯誤。 我認為,應改為:

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"));
});

這樣,您就可以更清晰地將關注點分離。

我希望這有幫助。

對於按鈕,您可以使用類似-

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

您的jQuery可能就像Moby提到的那樣-

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

這樣,如果除了加載新頁面外,還需要在jQuery中執行某些操作,則可以在其中執行,並讓函數確定是否重定向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM