簡體   English   中英

有沒有辦法在MVC4 ActionLink中為其中一個RouteValue參數調用JavaScript?

[英]Is there any way to call JavaScript in an MVC4 ActionLink for one of the RouteValue parameters?

我的頁面上有一個下拉列表(DropDownListFor)和一個ActionLink。 基本上,我遇到的問題是我正在嘗試從下拉列表中捕獲選定的值並將其作為ID傳遞到我的ActionLink中。 這是我的代碼:

@Html.DropDownListFor(x => x.Capsules, new SelectList(Model.Capsules, "pk", "name", "pk"))
<br />
@Html.ActionLink("Submit", "Create", 
    new { controller = "Process", id = /*JavaScript here to get the selected ID for the DropDownList above*/ },
    new { data_role = "button" })

對於我想要實現的目標,有沒有辦法將JavaScript嵌入到我的Html.ActionLink調用中? 如果沒有辦法,或者不推薦,請告知另一種解決方案來解決這個問題? 提前致謝!

您可以為id參數添加虛擬值,如下所示:

@Html.ActionLink("Submit", "Create", 
    new { controller = "Process", id = "dummy" },
    new { data_role = "button" })

然后在單擊鏈接時替換該值。

// Assuming your link's id is `submit`, and the dropdown's id is `capsules`
$('#submit').click(function() {
    var id = $('capsules').val();
    $(this).href = $(this).href.replace('dummy', id);
});

你可以通過使用javascript攔截鏈接來實現這一點Darin已經發布了一個這樣的例子

但是,看起來您正在嘗試使用ActionLink提交一些值,並且您可能最好創建一個包含所需值的viewmodel,然后使用提交按鈕發布所有值。 這允許您發布比ID更多的數據,防止您依賴Javascript,並保持所有代碼服務器端而不是混合和匹配。

根據您發布的小代碼判斷 - 您已經有了一個模型,可能是一些強類型實體,並且它有一個名為Capsules的屬性。

在控制器中,創建保存視圖數據的視圖模型:

public class YourViewModel
{
   YourModel YourModel { get; set; }

   public int CapsuleId { get; set; }
}

然后你的觀點:

@using( @Html.BeginForm( "Create", "Process"  ) )
{
@Html.DropDownListFor(m=> m.CapsuleId, new SelectList(Model.YourModel.Capsules, "pk", "name", "pk"))
<input type="submit">
}

然后你的控制器動作來處理這個:

[HttpPost]
public ActionResult Create( YourViewModel model )
{
   var id = model.CapsuleId;

  // do what you're going to do with the id
   return View();
}

暫無
暫無

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

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