[英]MVC - Pass value to controller via JS
我有一个下拉
<%=Html.DropDownList("genre", Model.genres, "", new { @onchange = ChangeMovie()" })%>
JavaScript看起来像(不完整)
function ChangeMovie() {
var genreSelection = container.find( '#genre' ).val();
$.ajax({
"url" : "/Movies/GetGenre" ,
"type" : "get" ,
"dataType" : "json" ,
"data" : { "selectedValue" : $( "#genre").val() },
"success" : function (data) {}
});
};
控制器代码
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.
}
我想通过js函数将下拉列表的选定值传递给控制器代码中的操作结果。 我需要帮助操作JavaScript代码和AJAX调用代码,以便将正确的值传递给控制器。
您在Ajax请求中发布的值的参数名称与Action参数名称不匹配。 selectedValue应该是genreName 。
改变这个:
"data" : { "selectedValue" : $( "#genre").val() },
对此:
data : { genreName : $("#genre").val() },
要使模型绑定正常运行,传递的json对象的字段名称应与控制器操作的参数名称匹配。 所以,这应该工作
"data" : { "genreName" : $( "#genre").val() },
你有很多不必要的引用,也没有在你的行动中返回JSON
$.ajax({
url: "/Movies/GetGenre/",
dataType: "json",
cache: false,
type: 'GET',
data: {genreName: $("#genre").val() },
success: function (result) {
if(result.Success) {
alert(result.Genre);
}
}
});
另外你的控制器没有返回Json,修改你的动作
public JsonResult GetGenre(string genreName) {
// do what you need to with genreName here
return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.