MVC - Pass value to controller via JS

2019-07-02 16:04发布

问题:

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.

回答1:

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


回答2:

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() },


回答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() },