3

I have a drop down

 <%=Html.DropDownList("genre", Model.genres, "", new { @onchange = ChangeMovie()" })%>

The JavaScript looks like (incomplete)

function ChangeMovie() {
    var genreSelection = container.find( '#genre' ).val();

    $.ajax({  
        "url" : "/Movies/GetGenre" ,
        "type" : "get" ,
        "dataType" : "json" ,
        "data" : { "selectedValue" : $( "#genre").val() },
        "success" : function (data) {}
    });
};

Conrtroller code

public ActionResult GetGenre(string genreName)
{
   //Need to get the `genreName` from the JavaScript function above.. which is
   // in turn coming from the selected value of the drop down in the beginning.

}

I want to pass the selected value of the drop down to the action result in the controller code via the js function. I need help manipulating the JavaScript code and the AJAX call code so the correct value is passed onto the controller.

3 Answers 3

3

You have a lot of unnecessary quotes as well not returning JSON in your action

$.ajax({
    url: "/Movies/GetGenre/",
    dataType: "json",
    cache: false,
    type: 'GET',
    data: {genreName: $("#genre").val() },             
    success: function (result) {
        if(result.Success) {
            alert(result.Genre);
        }
    }
});

Plus your controller isn't returning Json, modify your action to this

public JsonResult GetGenre(string genreName) {
    // do what you need to with genreName here 
    return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I just need to pass genre.. not the city. I edited the OP. Thank you
It's a dynamically created property, JSON lets you create properties on the fly. By adding Success = true, I just created a boolean property and set it to true on the fly. If you had an error you could set it to false and include a Message = whatever your error was. By adding Genre = genreName I'm just creating a property on the fly and giving back the value that was sent in. You can change it to whatever you want
No problem, glad that got it going for you!
3

For model binding to function correctly, field names of passed json object should match parameter names of your controller action. So, this should work

"data" : { "genreName" : $( "#genre").val() },

Comments

3

The parameter name of the value you're posting in the Ajax request does not match the Action parameter name. selectedValue should be genreName.

Change this:

"data" : { "selectedValue" : $( "#genre").val() },

to this:

data : { genreName : $("#genre").val() },

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.