How to get value selected in @Html.DropDownListFor inside the view and pass it to action in OTHER controller?
Asked Answered
D

3

5

I have a dropdown list. If user chooses to click Fetch call I want to pass id of selected Call to action FetchCall in controller Person.

<p>
    @Html.DropDownListFor(m => m.CallsToMake, new SelectList(Model.CallsToMake.OrderByDescending(call => call.TimeStamp), null), new { @class = "btn btn-default dropdown-toggle", style = "width: 500px;" })
</p>
<p>
     @Html.ActionLink("Fetch call","FetchCall", "Person", new { id = HERE_SELECTED_CALL_ID }, new { @class = "btn btn-info btn-lg" })
</p>

View is strongly typed against: @model WebApplication2.Models.ApplicationUser and is associated with Action Details in controller ApplicationUsers.

How to get value selected in @Html.DropDownListFor inside the view and pass it to action in OTHER controller in my case?


If it is not a problem I feel better with java script(I understand better what is going on).

EDIT

This is solution(mine) which lacks getting value from dropdown in java script function.

The dropdown list:

    @Html.DropDownListFor(m => m.CallsToMake, new SelectList(Model.CallsToMake.OrderByDescending(call => call.TimeStamp), null), new { @class = "btn btn-default dropdown-toggle", style = "width: 500px;" })

The button when clicked javascript:FetchCall() is invoked:

<input type="button" id="FetchCallButton" value="Fetch call" onclick="javascript:FetchCall()" />

The JavaScript function:

 function FetchCall() {
        var url = '@Url.Action("FetchCall, "Person")';  
        $.post(url, { callToMakeId: SELECTED_CALL_IN_DROPDOWN_ID_HOW_TO_GET_IT}, function (data) {
            alert('YES');
        });
    }

The action method in PersonController:

public ActionResult FetchCall(int callToMakeId) {...}

Question: How to get selected call.Id in the java script function?


EDIT 2

Thanks to Tommy's solution I've been able to read selection in dropdown list. The problem is that I get exacly what is written in the dropdown list which is result from ToString() inside CallToMake class.

function:

function FetchCall() {
    alert($("#CallsToMake").val());
    var url = '@Url.Action("FetchCall", "Person")';
    $.post(url, { callToMakeId: $("#CallsToMake").val() }, function (data) {
        alert('YES');
    });
}

I show in image below contents of the drop down and alert alert($("#CallsToMake").val());:

enter image description here

The only solution that comes to my mind is to display id of the call in the dropdown list and then cut it out in the controller action. It sounds bad, isn't it?

EDIT 3

The list finally looks like:

@Html.DropDownListFor(m => m.CallsToMake, new SelectList(Model.CallsToMake.OrderByDescending(call => call.TimeStamp), "Id","Id"), new { @class = "btn btn-default dropdown-toggle", style = "width: 500px;" })

java script:

    function FetchCall() {
        alert($("#CallsToMake").val());
        var url = '@Url.Action("FetchCall", "Person")';
        $.post(url, { callToMakeId: $("#CallsToMake").val() }, function (data) {
            alert('YES');
        });
    }
=

and the Action method

 public ActionResult FetchCall(int callToMakeId) {
            CallToMake callToMake = db.CallsToMake.Find(callToMakeId);
            int idPersonToCall = callToMake.Callee.Id;
            db.CallsToMake.Remove(callToMake);
            db.SaveChanges();
            Debug.WriteLine("I AM HERE");
            return RedirectToAction("Details", new { id = idPersonToCall });
        }

Action method is being invoked but I am not redirected anywhere. Method just runs and that is all.

Determined answered 15/9, 2014 at 21:3 Comment(8)
This link could help you #10500297Printmaker
You will need to use javascript/jquery.Cinquefoil
@StephenMuecke Could you please have a look at the edit? I posted solution with javascript which lacks getting selected value from the list in the script.Determined
@Yoda, Tommy's answer should work for youCinquefoil
@StephenMuecke It worked partialy as I can see what has been selected but cannot get to the id of selected value, I posted only solution that I can think of in EDIT 2.Determined
@Yoda, you need to construct the select list using the overload that accepts the values for text and value. I dont know the name of the properties, but it will be something like ..new SelectList(Model.CallsToMake, "NameofValueProperty", NameofTextProperty"). The NameofValueProperty is the ID property to want to get and the NameofTextProperty is what will be displayedCinquefoil
@StephenMuecke This worked! The deal is that I have not been redirected to the view action method in controller FetchCall returns. The action method runs to the en I used Debug.WriteLine to check it. I posted action method in EDIT 3.Determined
No, because you are doing an AJAX call (so you stay on the same page). I'll post an answer showing how to do a redirect.Cinquefoil
C
5

First you need to construct your SelectList using the overload that accepts a DataValueField and TextValueField. Refer documentation. This might look something like

... new SelectList(Model.CallsToMake, "CallID", "CallName"), ..

Script (this assumes you remove the onclick attribute from the button)

$('#FetchCallButton').click(function() {
  var url = '@Url.Action("FetchCall, "Person")';
  var callID = $("#CallsToMake").val();
  window.location.href = url + '/' + callID; // redirect to /Person/FetchCall/3
});
Cinquefoil answered 15/9, 2014 at 23:41 Comment(1)
I'm using Select tag helper. Using @Stephen's code I was able to get the id of selected item as follows: <select asp-for="SelectedProjYr" asp-items="Model.lstProjYears"></select> var selectedItemVal = $('#SelectedProjYr').val();Mica
Q
4

It should be straight-forward. The model property name will be the id of the element Razor generates - like this:

@Html.DropDownListFor(m => m.CallsToMake, new SelectList(Model.CallsToMake.OrderByDescending(call => call.TimeStamp), null), new { @class = "btn btn-default dropdown-toggle", style = "width: 500px;" })

would generate

<select id="CallsToMake" name="CallsToMake" class="btn btn-default dropdown-toggle" style="width: 500px">
    <option value="1">Some person</option>
</select>

Combining this knowledge with the jQuery call to get an element by id - $("#elementId"), we can then send the selected value back using an AJAX request.

function FetchCall() {
        var url = '@Url.Action("FetchCall, "Person")';  
        $.post(url, { callToMakeId: $("#CallsToMake").val()}, function (data) {
            alert('YES');
        });
    }
Qintar answered 15/9, 2014 at 22:40 Comment(4)
Tommy this solution enabled me to get selected contents from the dropdown list but I don't have access to the id, please look at EDIT 2. I presented there my results.Determined
This line was the both the most simple and the most useful thing I read today! The model property name will be the id of the element Razor generatesConverge
nice one and work well. if you can please tell me if we have more than one dropdownlist, how to call for both in script. I tried by changing the id, but then it returns only last one.No idea about that.If you can please help me with this. @QintarChrominance
@Qintar Using yours (as well as @StephenMueckes) code I was able to get the id in case of select tag helper as shown in my comment to @Stephens response above.Mica
C
0

thanx for @Tommy it works for me. but I had a problem about if I had to return from two dropdowlists how to do it in query. then I found a way and I think it will help to others.

function fetch(){
     var url = '@Url.Action("resultView","Test")';
            $.post(url, { LocationID: $("#location_ID").val(), TypeID:$("#type_ID").val() }, function (data) {
                alert('YES');
            });
}

this works for me fine.

Chrominance answered 19/11, 2015 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.