每个解决方案/类似问题都与 json 对象有关。我认为这个问题可能是由于使用html引起的。我还验证了数据在调用 ajax 之前不为空。
这是 Ajax
function SubmitSearch() {
var type = $("#select_SearchType").val()
var query = $("#input_Search").val()
$.ajax({
//url: "newSearch",
url: '@Url.Action("newSearch", "Results")',
type: 'POST',
cache: false,
dataType: "html",
contentType: 'application/html; charset=utf-8',
data: { type: type, query: query },
success: function (ViewModel) {
alert(ViewModel)
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
error: function (ViewModel) {
alert("error")
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
});
}
并从操作中选择代码
[HttpPost]
public ActionResult newSearch(string type, string query)
{
switch (type)
{
case " ":
response.errMess = "empty data, T:" + type + " Q:" + query;
return PartialView("Record", response);
default:
response.errMess = "Error: mismatched fields, T:" + type + " Q:" + query;
return PartialView("Record", response);
}
类型和查询都是空的
最佳答案
您不需要使用contentType: 'application/html; charset=utf-8'
。有一些方法。
首先,你必须使用这样的东西(直接将参数放在url
中):
$.ajax({
//url: "newSearch",
url: '@Url.Action("newSearch", "Results")?type='+type+'&query='+query,
type: 'POST',
success: function (ViewModel) {
alert(ViewModel)
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
error: function (ViewModel) {
alert("error")
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
});
第二。 您必须使用 data 将一些数据保存到服务器属性。
如果要返回PartialView
,则无需使用dataType: "html"
类似这样的事情:
$.ajax({
//url: "newSearch",
url: '@Url.Action("newSearch", "Results")',
type: 'POST',
cache: false,
data: { type: type, query: query },
success: function (ViewModel) {
alert(ViewModel)
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
error: function (ViewModel) {
alert("error")
$("#div_record").empty();
$("#div_record").html(ViewModel)
},
});
关于javascript - MVC : Ajax data not getting to Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151309/