Asp.net Ajax和MVC2 [英] Asp.net ajax with mvc2

查看:125
本文介绍了Asp.net Ajax和MVC2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话一个AJAX方法如下

I am calling a ajax method as below

 var srchText = "Chicago";


 $.ajax({
    url: "/Ajax/GetCities",
    data: "{'srchText' : '" + srchText + "'}",
    dataType: "json",
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    dataFilter: function (data) { return data; },
    success: function (data) {
        cityList = data.d;
    }
});

该链接指向一个MVC控制器,如下,

The url is pointing to a MVC controller, as below,

 [HttpPost]
    public ActionResult GetCities(string srchText)
    {
        List<City> result = new List<City>();
        EventsBIZ objBIZ = new EventsBIZ();
        result = objBIZ.ToList<City>(objBIZ.GetCities(srchText));
        return this.Json(new GetEventsResponse() { d = result }, JsonRequestBehavior.AllowGet);
    }

有一些是错误的code,该方法被成功调用,但srchText即将为空。请帮我找出笏出了错。在此先感谢

There is something wrong with the code, that the method is called successfully, but the srchText is coming as null. Please help me to figure out wat went wrong. Thanks in advance

添加从萤火跟踪的请求。

Adding the request tracked from firebug.

推荐答案

您code不工作的原因是因为默认情况下ASP.NET MVC 2没有的了解 JSON 请求。没有什么内置的,允许你发送一个JSON格式的请求,该请求被解析回一个强类型的操作参数。此功能是内置的默认情况下从ASP.NET MVC 3开始看看的<一个href=\"http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx\"相对=nofollow>以下博客帖子。你将需要实施 JsonValueProviderFactory 如果你想在ASP.NET MVC这项工作2

The reason your code doesn't work is because by default ASP.NET MVC 2 doesn't understand JSON requests. There is nothing built-in that allows you to send a JSON formatted request and that this request is parsed back to a strongly typed action argument. This functionality is built-in by default starting from ASP.NET MVC 3. Take a look at the following blog post. You will need to implement a JsonValueProviderFactory if you want to make this work under ASP.NET MVC 2.

此外,而不是:

data: "{'srchText' : '" + srchText + "'}",

你应该使用:

data: JSON.stringify({ srchText: srchText }),

JSON.stringify 原产现代的浏览器,并为老年人可能需要包含的 json2.js

The JSON.stringify is native for modern browsers, and for older you might need to include json2.js.

如果你不想实施 JsonValueProviderFactory 是使用标准的另一种可能性应用程序/ x-WWW的形式urlen codeD 请求,默认模式粘结剂可以了解:

Another possibility if you don't want to implement a JsonValueProviderFactory is to use a standard application/x-www-form-urlencoded request which the default model binder can understand:

$.ajax({
    url: '/Ajax/GetCities',
    data: { srchText: srchText },
    type: 'POST',
    async: false,
    dataType: 'json',
    dataFilter: function (data) { return data; },
    success: function (data) {
        cityList = data.d;
    }
});

这篇关于Asp.net Ajax和MVC2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆