RollerCosta
RollerCosta

Reputation: 5176

Jquery An ajax WIth html.dropdown

Situation is : when i select a value from a html.dropdown then i need corresponding values stored in another table at database with in the same view in any manner (keep dropdown visible).
My consideration:: Firstly i need to pass selected value of dropdown to some controller action(using jquery handler). then that controller action must return a partial view which i can display on dropdownlist view with the help of Ajax........need some code

Upvotes: 0

Views: 357

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use javascript to subscribe to the .change event of the dropdown list and trigger an AJAX request sending the selected value to the server. For example assuming you have the following dropdown (with an unique id so that it can be referenced more easily from your javascript files and an HTML5 data-* attribute pointing to the server controller action that will be invoked when the value changes):

@Html.DropDownListFor(
    x => x.SomeProperty, 
    Model.Items, 
    new { 
        data_url = Url.Action("Foo", "SomeController"),
        id = "myddl" 
    }
)

in a separate javascript file you could subscribe to the change event:

$(function() {
    // When the DOM is loaded subscribe to the .change event of the dropdown list
    // with id="myddl"
    $('#myddl').click(function() {
        // when the value of the dropdown changes fetch the new value
        var selectedValue = $(this).val();

        // fetch the url
        var url = $(this).data('url');

        // send the selected value to the server using a AJAX POST request
        $.post(url, { value: selectedValue }, function(result) {
           // will be called when the AJAX succeeds. Here you could process
           // any eventual results sent by the server. For example the server could
           // return some JSON object indicating whether the operation succeeded or not
        });
    });
});

which would invoke the corresponding action:

[HttpPost]
public ActionResult Foo(string value)
{
    // at this stage value will equal the selected dropdown value
    // so that you can update your database and do whatever you want with it
    ...
}

Upvotes: 1

Related Questions