2013-02-27 84 views
0

我在頁面上有一個下拉列表(DropDownListFor)和一個ActionLink。基本上,我遇到的問題是我試圖從我的下拉列表中捕獲選定的值,並將其作爲ID傳遞給我的ActionLink。這裏是我的代碼:有沒有辦法在MVC4 ActionLink中爲一個RouteValue參數調用JavaScript?

@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電話?如果沒有辦法,或者不推薦,可否請您提供另一種解決方案來解決這個問題?提前致謝!

+0

你用剃刀嗎? – 2013-02-27 04:12:49

+0

是的,我正在使用剃鬚刀。 – 2013-02-27 04:13:33

回答

1

您可以通過使用JavaScript達林有這個posted an example攔截的鏈接做到這一點。

但是,它看起來像是在嘗試使用ActionLink提交一些值,並且您最好創建一個包含所有想要的值的視圖模型,然後使用提交按鈕發佈所有內容。這允許您發佈更多的數據而不僅僅是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(); 
} 
+0

這看起來很有前途。今晚晚些時候我會試着實施你的建議!謝謝!! – 2013-02-28 18:17:50

1

你可以把假值這樣的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); 
}); 
+0

不幸的是,這不適合我。傳遞到下一頁的值是-1。即使用實際值代替「id」,在我的情況下,「3」。它沒有對我的網址做任何事情。 – 2013-02-27 04:31:11

+0

你有調試javascript嗎?當你的鏈接被點擊時它會被調用嗎? – 2013-02-27 04:32:40

+0

我一直都很難調試JavaScript,所以我不確定。這種方式似乎是一種解決方法...我想我以後是有一個共同的,記錄的方式來做到這一點?或者解決方法是唯一的選擇? – 2013-02-27 04:36:02

相關問題