2017-02-13 20 views
-1

我有具有車模一個DropDownList更改URL ID取決於DropDownList的選定值

@Html.DropDownList("Cars", (IEnumerable<SelectListItem>)ViewBag.Cars, "Select a Value", htmlAttributes: new { @class = "form-control" }) 我需要的用戶還必須選擇一個值,如果他選擇一個特定的值發送值的ID URL的動作作爲參數

<a href="@Url.Action("Edit", "Registration", new { id = selected value of the dropdownlist item })" class="text-white"> Modify Registration</a> <a href="@Url.Action("Delete", "Registration", new { id = selected value of the dropdownlist item })" class="text-white"> Cancel Registration</a>

回答

3

您將需要使用JavaScript來實現這一目標。因此,例如,你可以給你的錨的唯一ID:

<a id="editRegistration" href="@Url.Action("Edit", "Registration", new { id = "initial value from the database" })" class="text-white">Modify Registration</a> 

,然後訂閱下拉的變化事件,並更新錨的href:

<script> 
    $('#Cars').change(function() { 
     var url = "@Url.Action("Edit", "Registration", new { id = "#ID#" })"; 
     // replace the #ID# placeholder with the selected value 
     var newHref = url.replace('#ID#', this.value); 
     $('#editRegistration').attr('href', newHref); 

     // do the same with the other anchor 
    }); 
</script> 
+0

嗨,達林我不知道用戶將從下拉列表中選擇哪個值來評估'#ID#' –

+0

您不需要評估任何內容。這只是一個佔位符,你應該像我的答案中所示的那樣進行硬編碼。這個想法是,你使用javascript訂閱下拉菜單的onchange事件,並且在這個回調函數中,你只需用實際選定的值替換佔位符,並用新的url替換錨點的'href'屬性即可。 –

+0

這意味着我會採取代碼複製粘貼? –