MVC - pass value to controller via JS

I have a drop down list

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

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) {}
    });
};

Controller 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 list to the result of the action in the controller code through the js function. I need help managing JavaScript code and AJAX call code, so the correct value is passed to the controller.

+3
source share
3 answers

You have a lot of unnecessary quotes, and also 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 does not return Json, change your action to

public JsonResult GetGenre(string genreName) {
    // do what you need to with genreName here 
    return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}
+3
source

, Ajax, Action. selectedValue genreName.

:

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

:

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

To correctly bind the model to functions, the field names of the transferred json object must correspond to the parameter names of your controller action. So this should work

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

All Articles