jQuery делает GET с данными - параметры контроллера MVC равны нулю

Я делаю GET с помощью jQuery. Метод, который я вызываю, находится в моем контроллере (MVC-4), и метод имеет 1 параметр.

У меня есть данные, и я знаю, что строка данных действительна. Я также могу сказать, что мои опубликованные данные действительны в формате JSON, например:

{
    "txid": "051e30921f2886595ad9f22401437f10a77635c21b33b0e9e0aaefd52488e234-000"
}

Однако, когда я делаю команду GET, мой параметр на контроллере равен нулю. В FireBug я вижу, что вызов сделан, и я получаю следующую ошибку:

"NetworkError: 500 Internal Server Error - http://localhost:52705/Home/GetInformationAboutTransaction?{%22txid%22:%22051e30921f2886595ad9f22401437f10a77635c21b33b0e9e0aaefd52488e234-000%22}"

А с точкой останова в контроллере я могу запустить код контроллера с нулевым параметром.

Я ничего не менял в стандартном проекте MVC (без маршрутизации, без изменений global.asax).

Код:

 var txId = $('#infoTransactionTxIdBox').val();

            if (txId) {
                alert(txId);

                $.ajax({
                    type: "GET",
                    datatype: "json",
                    contentType: "application/json; charset=utf-8",
                    data: '{"txid":"' + txId + '"}',
                    url: "/Home/GetInformationAboutTransaction",
                    success: function (data) {
                        $('#infoAboutTransactionLbl').text(data);
                    }
                });
            } else {
                $('#infoAboutTransactionLbl').text('You need to enter a transaction id');
            }

Контроллер:

    [HttpGet]
    public JsonResult GetInformationAboutTransaction(string txid)
    {
        var rawTransaction = _baseBtcConnector.GetRawTransaction(txid);
        var infoAboutTransaction = _baseBtcConnector.DecodeRawTransaction(rawTransaction);
        return Json(infoAboutTransaction);
    }

Тег ответа:

GET http://localhost:52705/Home/GetBalanceInWallet

200 OK
        481ms   
jquery-1.9.1.js (line 8526)
GET http://localhost:52705/Home/GetInformationAboutT...01437f10a77635c21b33b0e9e0aaefd52488e234-000%22}

500 Internal Server Error
        9.47s   
jquery-1.9.1.js (line 8526)
ParamsHeadersResponseHTMLCookies

<!DOCTYPE html>
<html>
    <head>
        <title>The remote server returned an error: (500) Internal Server Error.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>The remote server returned an error: (500) Internal Server Error.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.Net.WebException: The remote server returned an error: (500) Internal Server Error.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

Line 84: 
Line 85: 
<font color=red>Line 86:                 WebResponse webResponse = rawRequest.GetResponse();
</font>Line 87: 
Line 88:                 streamReader = new StreamReader(webResponse.GetResponseStream(), true);</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <b> Source File: </b> c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseConnector.cs<b> &nbsp;&nbsp; Line: </b> 86
            <br><br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +6442408
   BitcoinWrapper.Wrapper.BaseConnector.RequestServer(MethodName methodName, List`1 parameters) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseConnector.cs:86
   BitcoinWrapper.Wrapper.BaseConnector.RequestServer(MethodName methodName, Object parameter) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseConnector.cs:45
   BitcoinWrapper.Wrapper.BaseBtcConnector.GetRawTransaction(String txid) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseBtcConnector.cs:44
   ClientTest.Controllers.HomeController.GetInformationAboutTransaction(String txid) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\ClientTest\Controllers\HomeController.cs:37
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass42.&lt;BeginInvokeSynchronousActionMethod&gt;b__41() +28
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass8`1.&lt;BeginSynchronous&gt;b__7(IAsyncResult _) +10

   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass39.&lt;BeginInvokeActionMethodWithFilters&gt;b__33() +57
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4f.&lt;InvokeActionMethodFilterAsynchronously&gt;b__49() +223
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass37.&lt;BeginInvokeActionMethodWithFilters&gt;b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2a.&lt;BeginInvokeAction&gt;b__20() +24
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass25.&lt;BeginInvokeAction&gt;b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.&lt;&gt;c__DisplayClass1d.&lt;BeginExecuteCore&gt;b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9

   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700

   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045

            </font>

    </body>
</html>
<!-- 
[WebException]: The remote server returned an error: (500) Internal Server Error.
   at System.Net.HttpWebRequest.GetResponse()
   at BitcoinWrapper.Wrapper.BaseConnector.RequestServer(MethodName methodName, List`1 parameters) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseConnector.cs:line 86
   at BitcoinWrapper.Wrapper.BaseConnector.RequestServer(MethodName methodName, Object parameter) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseConnector.cs:line 45
   at BitcoinWrapper.Wrapper.BaseBtcConnector.GetRawTransaction(String txid) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\BitcoinWrapper\Wrapper\BaseBtcConnector.cs:line 44
   at ClientTest.Controllers.HomeController.GetInformationAboutTransaction(String txid) in c:\Users\LarsHoldgaard\Documents\GitHub\bitcoin-wrapper\ClientTest\Controllers\HomeController.cs:line 37
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)

   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

"NetworkError: 500 Internal Server Error - http://localhost:52705/Home/GetInformationAboutTransaction?{%22txid%22:%22051e30921f2886595ad9f22401437f10a77635c21b33b0e9e0aaefd52488e234-000%22}"
GetInf...4-000"}

person Lars Holdgaard    schedule 23.06.2013    source источник
comment
Не могли бы вы предоставить содержимое вкладки Response, захваченное в Firebug?   -  person Mikhail    schedule 23.06.2013
comment
@Mikhail - тег ответа добавлен :-)   -  person Lars Holdgaard    schedule 23.06.2013


Ответы (1)


По умолчанию ASP.NET MVC не возвращает JSON из запроса GET. Вам нужно добавить JsonRequestBehavior.AllowGet к вашему возврату.

data: '{"txid":"' + txId + '"}'

тоже кажется неверным. Пытаться

data: { txid : txId }

Я думаю, что когда вы используете строку в качестве свойства data, вы на самом деле не отправляете именованный параметр в контроллер, поэтому связывателю модели нечего связывать. Предлагаемая версия должна это исправить.

person Tieson T.    schedule 23.06.2013
comment
@LarsHoldgaard Казалось неверным после просмотра вашего последнего редактирования. Предположим, я могу добавить его обратно в... - person Tieson T.; 23.06.2013
comment
Истинный. Я не понимаю, почему это сработало, но раньше случались более странные вещи :-) Большое спасибо. Я приму как ответ! - person Lars Holdgaard; 23.06.2013
comment
@LarsHoldgaard Хорошо, я добавил эту часть обратно с объяснением, почему я думаю, что это сработало. В основном для тех, кто столкнется с этим вопросом в будущем. - person Tieson T.; 23.06.2013