问题描述
我创建了一个视图和控制器,我想返回一些搜索结果的控制器。我使用jQuery的呼叫控制器
<输入类型=文本ID =标题/>
< A HREF =#ID =搜索>搜索和LT; / A>
<脚本>
$(#搜索)。点击(函数(){
警报('称为');
VAR P = {数据:$('#搜索)VAL()};
$阿贾克斯({
网址:'/配料/搜索',
键入:POST,
数据:JSON.stringify(P),
数据类型:JSON
的contentType:应用/ JSON的;字符集= UTF-8,
成功:功能(数据){
警报(数据);
},
错误:函数(){
警报(错误);
}
});
});
我的控制器看起来像这样
[HttpPost]
公众的ActionResult搜索(字符串输入)
{
VAR的结果= _db.Ingredients.Where(I => i.IngredientName ==输入); 返回新JsonResult(){数据=新的{NAME =你好}};
}
我的问题是我不知道如何从我的jQuery调用到控制器的varible,我已经把一个断点在控制器上和被击中但是输入字符串总是空。
我做了什么错?
<输入类型=文本ID =标题/>
@ Html.ActionLink(搜索,搜索,配料,空,新的{ID =搜索})
,然后悄悄地AJAXify此链接在一个单独的JavaScript文件:
$(函数(){
$(#搜索)。点击(函数(){
$阿贾克斯({
网址:this.href,
输入:POST,
数据:{输入:$('#标题)VAL()},
成功:函数(结果){
警报(result.name);
},
错误:函数(){
警报(错误);
}
});
返回false;
});
});
在您的控制器动作看起来是这样的:
[HttpPost]
公众的ActionResult搜索(字符串输入)
{
VAR的结果= _db.Ingredients.Where(I => i.IngredientName ==输入);
// TODO:使用结果变量的匿名对象
//这被作为JSON给客户端
返回JSON(新{NAME =你好});
}
I have created a view and a controller, the controller I am wanting to return some search results. I am calling the controller using jquery
<input type="text" id="caption" />
<a href="#" id="search">Search</a>
<script>
$("#search").click(function () {
alert('called');
var p = { Data: $('#search').val() };
$.ajax({
url: '/Ingredients/Search',
type: "POST",
data: JSON.stringify(p),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
});
My controller looks like this
[HttpPost]
public ActionResult Search(string input)
{
var result = _db.Ingredients.Where(i => i.IngredientName == input);
return new JsonResult() {Data = new {name="Hello There"}};
}
My problem is I am not sure how to get the varible from my jquery call into the controller, I have put a breakpoint on the controller and its been hit however the input string is always null.
What have I done wrong?
<input type="text" id="caption" />
@Html.ActionLink("Search", "Search", "Ingredients", null, new { id = "search" })
and then unobtrusively AJAXify this link in a separate javascript file:
$(function() {
$("#search").click(function () {
$.ajax({
url: this.href,
type: 'POST',
data: { input: $('#caption').val() },
success: function (result) {
alert(result.name);
},
error: function () {
alert("error");
}
});
return false;
});
});
where your controller action could look like this:
[HttpPost]
public ActionResult Search(string input)
{
var result = _db.Ingredients.Where(i => i.IngredientName == input);
// TODO: Use the result variable in the anonymous object
// that is sent as JSON to the client
return Json(new { name = "Hello There" });
}
这篇关于使用jQuery的ajax参数传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!