0

I have a drop down list

<select onchange="alert(this.value);">
                    <option selected="selected" value="cat">cat</option>
                    <option value="dog">dog</option>
</select>

I would like to make it so that when the users changes a value then an AJAX call is sent to my MVC controller which then updates the database.

I've done this with forms but never from javascript. Does anyone have an example of how this could be done.

thanks,

1 Answer 1

1

If you are using jQuery:

<select id="category" name="category">
    <option selected="selected" value="cat">cat</option>
    <option value="dog">dog</option>
</select>

and then:

$(function() {
    $('#category').change(function() {
        $.post('/home/save', { selectedCategory: $(this).val() }, function(result) {
            alert('success');
        });
    });
});

which will send an AJAX request to the following action:

[HttpPost]
public ActionResult Save(string selectedCategory)
{
    // TODO: process the selected category
    return Json(new { success = true });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your quick reply. What about without using jQuery? I've stayed away from using this as I like to keep everything simple and I'd like to make my page as quick to load as possible. Not sure if this makes a difference but I'm using MVC3.
@Hiroki, jQuery is shipped by default in ASP.NET MVC 3 and I would strongly suggest you using it. The amount of javascript code that you will need to write in plain javascript in order to achieve the same functionality (working cross browser) simply is not worth it. Of course you could still do it using plain javascript. Define a custom function that you would invoke in the onchange event and then put your AJAX code in there.
Sorry to bother you with more complexity but I'd also like to send the value of another field to the action. How do I fit that into the above call? thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.