【发布时间】:2013-01-08 21:02:52
【问题描述】:
目前使用 MVC3 并使用 jQuery $.post 函数将 ajax 请求发送到名为“SearchInitiated”的控制器操作。我在这里有点头疼,因为我不确定我的问题到底出在哪里。我确定这是我忽略的一些小问题。
当我从 AJAX 调用中调用我的 Controller 方法时,我将一个 json 对象(字符串化)传递给一个控制器操作。见下文:
来自 Chrome 的请求标头
Accept:/ Content-Type:application/x-www-form-urlencoded; charset=UTF-8 用户代理:Mozilla/5.0(Windows NT 6.1;WOW64) AppleWebKit/537.17(KHTML,像 Gecko)
Chrome/24.0.1312.52 Safari/537.17
X-Requested-With:XMLHttpRequest
表单数据视图
connectorId:1
sessionId:97e2d8b2-be9e-4138-91ed-42ef9c6a2cd6
派对: {"Tag":null,"PartyIdentifier":"1","Address":null,"Address2":null,"BusinessName":"","CellPhoneNumber":null,"CIF":"","City" :null,"Country":null,"DateOfBirth":null,"EMailAddress":null,"EmploymentTitle":null,"EmployerAddress":null,"EmployerAddress2":null,"EmployerCity":null,"EmployerName":null ,"EmployerPhoneNumber":null,"EmployerState":null,"EmployerZip":null,"Fax":null,"Firstname":"TEST","Lastname":"USER","MailingAddress":null,"MailingAddress2" :null,"MailingCity":null,"MailingState":null,"MailingZip":null,"Middlename":null,"PhoneNumber":null,"State":null,"TIN":"1111111","WorkPhoneNumber" :null,"Zip":null}
javascript
var parties = @(Html.Raw(Json.Encode(Model.SearchParties)));
function SearchForCustomer(id)
{
var currentSelectedParty = GetPartyById(id)
//SearchPost is a wrapper for $.ajax using default values for dataType and contentType
SearchPost(URL, {
'connectorId': '@Model.ConnectorId',
'sessionId': '@Model.SessionId',
'party' : JSON.stringify( currentSelectedParty )
}
}
控制器
public ActionResult SearchInitiated(int connectorId, string sessionId, SearchParty party)
{
code here....
}
public class SearchParty
{
public SearchParty();
public SearchParty(string lastname, string firstname);
public string Address
{
get;
set;
}
public string City
{
get;
set;
}
public string Country
{
get;
set;
}
public string DateOfBirth
{
get;
set;
}
.... etc etc
}
但是,party 对象为空。
如果我将代码更改为以下内容,所有内容都会正确反序列化为强类型对象。
public ActionResult SearchInitiated(int connectorId, string sessionId, string party)
{
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
SearchParty sp =
json_serializer.Deserialize<SearchParty>(party);
}
我知道我的 json 字符串是有效的,因为它在第二个代码 sn-p 中工作,并且值正在调用中传递。我还能错过什么?
【问题讨论】:
-
您可以向我们发送您通过邮寄发送的示例请求吗?
-
为什么不让框架为您完成工作呢?将签名更改为:
public ActionResult SearchInitiated(int connectorId, string sessionId, SearchParty party),您不必手动反序列化。如果这不起作用,则说明您有问题,因此请将您要发送的数据发布到此操作。 -
另外,我看到您在声明中指定了“完整”类名,但在反序列化中没有指定。在这种情况下是否还有其他名为
SearchParty的类? -
我已经用更多信息更新了这个问题
标签: asp.net-mvc json asp.net-mvc-3