gpt4 book ai didi

javascript - MVC : Ajax data not getting to Controller

转载 作者:行者123 更新时间:2023-11-29 21:12:21 25 4
gpt4 key购买 nike

每个解决方案/类似问题都与 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)
},
});
}

并从 Action 中选择代码

    [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;字符集=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 将一些数据保存到服务器属性(property)。

如果要返回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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com