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