3

I have a code block in my MVC view as follows:

<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
     { %>
          <%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
                 <%} %>

I want to set the value of ViewData["selected"] so that i can send it to the desired action. Can anyone please suggest how can i do this?

thanks!

3 Answers 3

13

Instead of using a form, why not use a jQuery onChange event on your drop down?

$(document).ready(function() {
    $("#ddl").change(function() {
        var strSelected = "";
        $("#ddl option:selected").each(function() {
            strSelected += $(this)[0].value;
        });
        var url = "/Home/MyAction/" + strSelected;

        $.post(url, function(data) {
            // do something if necessary
        });
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct answer on how to do it with a form and ASP.MVC. stackoverflow.com/q/10566923/706363
some use $.ajax({ and you are using $.post, so what is the difference which is best for ajax Get and Post ?
2

ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).

Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.

1 Comment

@Elisabeth This is super old, but I couldn't help but notice your comment: When Ricky posted this, MVC 2.0 had only been released for about 2 months, so it was a legitimate link at the time :-)
0

Found solution at this post it is just small chnge

Yes, that’s right – only change is replacing:

onchange = “this.form.submit();”

with:

onchange = “$(this.form).submit();”

Comments

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.