[英]How do I select a value of a dropdown in MVC by using javascript?
我在我的cshtml頁面中使用此下拉列表。 它的優點
new SelectListItem
{
Value = x.TitleID.ToString(),
Text = x.TitleDescription
});
@Html.DropDownListFor(model => model.UserLoginModels.TitleID, Model.UserLoginModels.Title, new { @class = "form-control", @id = "title" })
我需要使用javascript選擇一個值
我嘗試過這種方式。
var dlTitle = $("#userCreate #title").data("kendoDropDownList");
$("#title").Value(3);
但是它給出了“ dlTitle未定義”
由於id
是唯一的,因此您只需要使用:
var dlTitle = $("#title").data("kendoDropDownList")
以及在定義控制台之前檢查是否正在使用dlTitle
,因為從控制台日志中收到該錯誤。
1.您應遠離ID為最后一個后代的后代選擇器。 ID應該是唯一的,並且只能應用於每頁單個DOM元素。 在您的情況下,您正在使用2個ID的$("#userCreate #title")
嘗試訪問ID為#title
的DOM元素。 話雖如此,它看起來應該如下所示:
var dlTitle = $("#title").data("kendoDropDownList");
2.如果您嘗試與Kendo UI DropDownList進行交互,則上述代碼將通過jQuery.data()來訪問DropDownList的實例,如示例var dlTitle = $("#title").data("kendoDropDownList");
。 這將為您提供對該實例的引用。
要檢索當前選定選項的值,您需要在ASP.NET MVC聲明的Kendo DropDownList之后放置以下內容:
@* razor view logic for your DropDownList goes here *@
<script type="javascript">
$(function() {
// Retrieve an instance of the DropDownList
var dlTitle = $("#title").data("kendoDropDownList");
// Log the output of the currently selected value of the DropDownList
console.log(dlTitle.val());
});
</script>
將此腳本塊放置在ASP.NET MVC聲明之后非常重要。 否則,您將遇到在DropDownList有機會實例化之前調用腳本的情況。
3.如果您打算設置DropDownList的值,則可以執行以下操作:
@* razor view logic for your DropDownList goes here *@
<script type="javascript">
$(function() {
// Retrieve an instance of the DropDownList
var dlTitle = $("#title").data("kendoDropDownList");
// Set the value of the DropDownList to the
// 4th option in the list
dlTitle.val(3);
// Set the value of the DropDownList to the option
// in the list that has a value of `foobar`
dlTitle.val('foobar');
});
</script>
請注意,此處與第2點一樣,此處需要確保在ASP.NET MVC聲明之后放置腳本塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.