使用 Jquery Ajax 和可变数据渲染部分视图
我已经阅读了这篇文章,但我不确定是否知道如何从用户那里获取数据。这是我正在使用的ajax jquery。我知道(或者至少认为)这不能渲染部分内容。但它会一直有效,直到渲染失败。我认为这可能会有所帮助。
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{'test':" + "'" + dateText + "'}",
dataType: 'json',
url: 'Site/Grab/',
success: function (result) {
alert('Success');
},
error: function (error) {
alert('Fail');
}
});
这是我的控制器
[HttpPost]
public ActionResult Grab(string test)
{
DateTime lineDate= Convert.ToDateTime(test);
List<Info> myInfo= GameCache.Data(lineDate);
return PartialView("_PartialView", myInfo);
}
I have already read this post, but I am not sure know to make it work taking data from the user. Here is the ajax jquery I am using. I know (or at least think) that this cant render a partial. But it works all the way until the render fails. I thought it may be helpful to have.
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{'test':" + "'" + dateText + "'}",
dataType: 'json',
url: 'Site/Grab/',
success: function (result) {
alert('Success');
},
error: function (error) {
alert('Fail');
}
});
Here is my controller
[HttpPost]
public ActionResult Grab(string test)
{
DateTime lineDate= Convert.ToDateTime(test);
List<Info> myInfo= GameCache.Data(lineDate);
return PartialView("_PartialView", myInfo);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,有几件事需要尝试:
1)
dataType
是 ajax 调用的预期结果。在您的情况下,您发送 JSON,但接收 HTML。content-type
参数指定您拥有的请求(并且您拥有的请求是正确的)。所以数据类型应该是:2)你需要序列化JSON。尝试使用轻量级 JSON 库和 stringify'ing:
比尝试使用引号强制 JSON 字符串容易得多。创建一个常规 JS 变量,然后将其字符串化。
你的代码的其余部分看起来不错。
如果部分视图本身的 HTML/标记有问题,请在调试模式下运行,Visual Studio 应停止在导致问题的标记行上。
额外提示:ASP.NET MVC 3 包含内置 JSON 模型绑定。因此,您可以创建一个与 JSON 对象的字段相匹配的基本 POCO,然后在操作方法中将其接受为强类型对象:
由于您只发送一个参数,所以这是多余的 - 但如果您有超过 2 个参数,那么这是值得的使用 JSON POCO。
Okay, couple of things to try:
1)
dataType
is the expected result of the ajax call. In your case, your sending JSON, but receiving HTML. Thecontent-type
parameter specifies the request, which you have (and what you have is correct). So the data type should be:2) You need to serialize the JSON. Try grabbing the lightweight JSON library and stringify'ing:
Much easier than trying to coerce a JSON string with quoatations. Create a regular JS variable, then stringify it.
The rest of your code looks fine.
If it's a problem with the HTML/markup of the partial view itself, run in debug mode and Visual Studio should stop on the line in the markup that is causing the problem.
Bonus Hint: ASP.NET MVC 3 includes built-in JSON model binding. So you can create a basic POCO that matches the fields of your JSON object, then accept it as a strongly-typed object in the action method:
Since your only sending one parameter, it's overkill - but if you have more than 2 then it's worthwhile using a JSON POCO.
将控制器代码更改为:
Change your controller code to: