-2

I have a dropdown in my view which is something like 'All, Read/Unread, Categories'. The view renders notifications for a user.

In the controller there's a default ActionResult to show all, one for read/unread, and one for something to do with categories.

I would like to use a factory to call one of the methods based on the dropdown selected as above (i.e unread selected calls unread ActionResult, the reason being I don't want to use switch/if statements to maintain maintainable code, I'm just not sure of the implementation.

1 Answers1

1

Why not use the correct URLs as values of the SelectListItem and use this value to redirect/load the content?

In your ViewModel for the GET use case:

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
     }
};

In your razor view:

@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>
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • Thank you for your response :).val() gets the text value in the dropdown (which is probably expected) rather than the Value attribute in the ViewModel. – Lewis Richardson Aug 08 '17 at 11:51
  • That is unexpected. If you have an ``, `.val()` should return `"/Notification/GetAll"` and `.text()` should return `"All"`. I guess this has to do with how you create the SelectListItems. You can not access the C# model directly using JavaScript. See also https://stackoverflow.com/questions/13089944/jquery-get-selected-option-value-not-the-text-but-the-attribute-value – Georg Patscheider Aug 08 '17 at 14:34