我在我的視圖中有一個下拉菜單,就像'全部,讀取/未讀,分類'。該視圖爲用戶呈現通知。使用工廠來調用不同的ActionResult?
在控制器中有一個默認的ActionResult顯示全部,一個用於讀取/未讀,一個用於類別。
我想使用工廠調用基於上面選擇的下拉列表中的一種方法(即未讀選定的調用未讀ActionResult,原因是我不想使用switch/if語句來維護可維護的代碼,我只是不知道執行
我在我的視圖中有一個下拉菜單,就像'全部,讀取/未讀,分類'。該視圖爲用戶呈現通知。使用工廠來調用不同的ActionResult?
在控制器中有一個默認的ActionResult顯示全部,一個用於讀取/未讀,一個用於類別。
我想使用工廠調用基於上面選擇的下拉列表中的一種方法(即未讀選定的調用未讀ActionResult,原因是我不想使用switch/if語句來維護可維護的代碼,我只是不知道執行
爲什麼不使用正確的網址作爲SelectListItem
的值,並使用這個值來重定向/加載內容
在您的視圖模型的GET使用情況。?
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
var availableOptions = new List<SelectListItem> {
new SelectListItem {
Text = "All",
Value = urlHelper.Action("GetAll", "Notifications"),
Selected = true
},
new SelectListItem {
Text = "Read/Unread",
Value = urlHelper.Action("GetReadOrUnread", "Notifications"),
Selected = false
},
new SelectListItem {
Text = "Categories",
Value = urlHelper.Action("GetCategories", "Notifications"),
Selected = false
}
};
在你的剃鬚刀視圖中:
@Html.DropDownListFor(m => m.SelectedView, Model.AvailableOptions)
<script>
$(document).ready(function() {
// use @Html.IdFor so this does not break
// if you rename the SelectedView property in the ViewModel
var dropdown = $('#@Html.IdFor(m => m.SelectedView)');
dropdown.on('change', function() {
// this gets the "value" attribute of the selected option
var selectedUrl = $('option:selected', dropdown).val();
$.ajax({
url: selectedUrl,
success: function(result){ /* insert retrieved HTML into DOM ... */ }
});
});
});
</script>
感謝您的迴應:)。val()獲取下拉列表中的文本值(這可能是預期的),而不是ViewModel中的Value屬性。 –
這是意想不到的。如果您選擇了<選項值=「/通知/ GetAll」>全部','.val()'應該返回'「/ Notification/GetAll」'並且'.text()'應該返回''全部「 '。我想這與你如何創建SelectListItems有關。您無法直接使用JavaScript訪問C#模型。另見https://stackoverflow.com/questions/13089944/jquery-get-selected-option-value-not-the-text-but-the-attribute-value –
你的問題是什麼? – Milney