Robin-Hoodie
Robin-Hoodie

Reputation: 4974

How to get a Selecteditem from a dropdownlist in a view?

So I have the following code in my view:

<div class="editor-field">
        @Html.DropDownList("EventId", String.Empty)   
        @Html.ValidationMessageFor(model => model.Events)
        @Html.ActionLink(null, "AddEvent", "OtherMeeting", new { eventId = ??)  
</div>

At the "??" I wish to get the selected value, only I have no idea how to get the selected value since the list isn't defined in a variable, nor do I seem to be able to give it a name property or something similar to get to the list itself.

Upvotes: 0

Views: 365

Answers (1)

von v.
von v.

Reputation: 17108

@Html.ActionLink(null, "AddEvent", "OtherMeeting", new { eventId = ??)
At the "??" I wish to get the selected value

Not possible since ActionLink happens on the server side and changing your dropdown happens on the client-side. There's a workaround but I like to answer your next issue first:

nor do I seem to be able to give it a name property or something similar to get to the list itself

When you do a @Html.DropDownList("EventId") the razor engine will give it both a name and an id and both will have the same value and that is EventId. You can use that id for whatever suit your puspose. The markup that will be written will look like this:

<select id="EventId" name="EventId">

A couple of things first before we solve your issue:

  1. You need to assign a seletlist to the DropDownList("EventId")
  2. You don't have a link text on ActionLink?

Now to solve your issue, you need to change your ActionLink to the following, giving it an id (and a text which is optional but make sense to have)

@Html.ActionLink("Add Event", "AddEvent", "OtherMeeting", new { id="eventLink" })

Then rebuild your action link, now an a tag in jquery everytime a selection is changed:

$("#EventId").change(function () {
    $("#eventLink").attr(
        'href',
        '@Url.Action("AddEvent","OtherMeeting")/' + $(this).val()
        );
});

Upvotes: 1

Related Questions