MVC Ajax:如何将字符串从视图发送到控制器



与发送 json 对象相比,我发现通过 ajax 发送纯文本(字符串(是一个小问题。

我目前有这个设置工作

(cs(html

<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />

脚本

<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET", 
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

和电流控制器

public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);

}

我只想向控制器发送一个直字符串,我尝试了这个脚本

function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET", 
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}

使用此控制器

public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);

}

但是这不起作用,显示输入字符串以获取 null 的值,并且 Ajax 给出了错误。我目前不知道如何解决此问题,也不知道是什么导致了错误。如果有人能指出我正确的方向,我将不胜感激

您可以在此处简单地使用$.get函数,其次,您应该使用Ùrl.Action帮助程序来获取控制器操作方法的 url,因为魔术字符串会导致应用程序可能部署在子目录中的部署中出现问题,在这种情况下,url 变得错误:

$.get('@Url.Action("SearchResults","Home")?input='+invalue , function (data) {  
if (data.success) {
alert(data.message);
}
});  

您可以轻松地将其作为请求参数传递,因为您还将类型设置为"GET"。

url: "/Home/SearchResults?input="+invalue

您还必须删除数据属性。让我知道它是否有帮助。

更新的答案数据类型是您希望从服务器返回的数据类型。内容类型是您发送的内容。因此,要返回视图,请将数据类型更改为 htmL。

dataType: 'html',

问题是,当您调用函数 sendtoC 时,您不会在函数中接收任何参数。更改函数以接受参数。

var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET", 
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}

最新更新