2015-10-26 54 views
0

我有一個選擇列表,看起來像這樣:C#剃鬚刀 - 凡在價值循環顯示評論等於的selectedIndex值

<select class="form-control"> 
    <option>Select</option> 
    <option value="2">Order</option> 
    <option value="5">Delivery</option> 
    <option value="6">PickUp</option> 
    <option value="13">Quote</option> 
</select> 

一旦用戶選擇的選項,我想顯示評論僅在db_Type =所選擇的選項的值:

foreach (var note in Model.GetNotes) 
    { 
     <div class="current-note-container"> 
      <h5 class="note-comment"><b>Description:</b><br/> @note.db_Comment.Where(note.db_Type == /* Selected Index */)</h5> 
     </div> 
    } 

我真的不知道我怎麼能做到這一點使用剃鬚刀,或者如何在混合JavaScript來完成這項工作。

+0

您正在使用哪個版本的MVC? – Franco

+0

對不起,應該添加標籤 - MVC 4 – cfly24

+1

爲什麼不通過JQuery做到這一點? C#是服務器端腳本,而JQuery是爲這些事情設計的客戶端腳本 –

回答

0

Razor是一個服務器端代碼,所以你不能將它與你正在計劃的客戶端腳本結合起來。

取而代之,使用jQuery來收聽selection changed event並將新選定的值傳回(GET/POST)回控制器和查詢數據庫並獲得所需的註釋。

jQuery的內部查看(僞代碼):

$("#ddlOptions").change(function() { //assuming ddlOptions is the Id of select list 
    var selectedOptionId= $(this).val();    
    $.get('@Url.Action("ActionName","ControllerName")', { id: selectedOptionId}, 
     //You can use $.get(...) or $.post(...) based on action method type. 
     function (data) { 
      //Display/append the comment received to a container(div/span etc) 
    }); 
}); 

控制器代碼(僞代碼)

public JsonResult Get(int id) 
{ 
    //Query database here based on id to get the comment 
    //e.g: db_comment.where(com=>com.id==id).FirstOrDefault(); 

    return Json(comment,JsonRequestBehavior.AllowGet); 
} 

希望這爲您提供了一些思路。

0

這是不準確的,但我認爲你在尋找這樣的事情

<select class="form-control" onchange="GetComment(this.value)"> 
    <option>Select</option> 
    <option value="2">Order</option> 
    <option value="5">Delivery</option> 
    <option value="6">PickUp</option> 
    <option value="13">Quote</option> 
</select> 

添加到您的Razor視圖的腳本

function GetComment(ID) 
{ 
    var parameters = {}; 

    parameters["ListID"] = ID; 

    $.ajax 
    ({ 
     type: "GET", 
     data: parameters, 
     url: "/MyController/GetComment", 
     success: function (message) { 
      $('#note-comment').val(message); 
     }, 
     error: function() { 
      alert("error"); 
     } 
    }); 
} 

最後是這樣的到您的控制器

[HttpGet] 
public JsonResult GetComment(int ListID) 
{ 
    return Json(Mylist[ListID].Comment); 
}