簡體   English   中英

ASP.NET MVC如何在javascript中獲取選定對象的某些字段?

[英]ASP.NET MVC How to get certain field of selected object in javascript?

對於控制器,我需要從該選擇器列表中提取CustomerID。

對於javascript中的頁面行為,我還需要從選定的Customer對象中獲取Customer的出生年份(比方說,來自Customer.DOB字段)

請問我該如何實現?

<select id="customerSelector" name="CustomerID">
   <option selected="selected" value="-1">Select Customer</option>
   @foreach (Customer c in Model.Customers)
   {
      // display customers in selector list
   }
   <option value="@c.CustomerID">@CustomerFullName</option>
</select>

<script>
   // get selected customer year of birth
</script>

您可以為下拉列表設置onChange事件,並使用jQuery從選定選項中讀取數據屬性,如下所示:

select id="customerSelector" name="CustomerID">
   <option selected="selected" value="-1">Select Customer</option>
   @foreach (Customer c in Model.Customers)
   {
      <option data-birthyear="@c.BirthYear" value="@c.CustomerID">@CustomerFullName</option>
   }
</select>

那么您的腳本將如下所示:

$('#customerSelector').change(function(){
    var birthYear = $(this).find(':selected').data('birthyear');
});

請注意,這是假設您的模型擁有代表客戶出生年份的某些屬性。 在這里,我假設Customer類具有一個名為BirthYear的屬性。 如評論中所述,我還建議使用.net mvc時使用剃刀HTML助手來創建html元素。

暫無
暫無

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

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