2011-01-18 5 views
1

私はMVCアクション.....WebRequestクラスMVC HttpPost DateTime型の書式

[HttpPost] 
public ActionResult DoStuff(string myString, DateTime myDateTime) 

を持っている...と私は

.....そうのようなコンパクトなフレームワークアプリケーションからアクションを呼んでいます
WebRequest request = WebRequest.Create(url); 

     // Set the Method property of the request to POST. 
     request.Method = "POST"; 
     request.Proxy = null; 

     // Create POST data and convert it to a byte array. 
     string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString(); 

     byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData); 

     // Set the ContentType property of the WebRequest. 
     request.ContentType = "application/x-www-form-urlencoded"; 

     // Set the ContentLength property of the WebRequest. 
     request.ContentLength = byteArray.Length; 

     // Get the request stream. 
     using (Stream dataStream = request.GetRequestStream()) 
     { 
      dataStream.Write(byteArray, 0, byteArray.Length); 
     } 

     // Get the response. 
     using (WebResponse response = request.GetResponse()) 
     { 
      // Display the status. 
      // Console.WriteLine(((HttpWebResponse)response).StatusDescription); 

      // Get the stream containing content returned by the server. 
      using (Stream responseStream = response.GetResponseStream()) 
      { 
       // Read the response... 
       using (StreamReader reader = new StreamReader(responseStream)) 
       { 
        Console.WriteLine(reader.ReadToEnd()); 
       } 
      } 
     } 

問題は "myDateTime"パラメータは常にnullですか? postDataの文字列は、これを動作させるためにはどのような形式でなければなりません(私はかなり試しました!)。

多くのおかげで、

ETFairfax

+0

問題は、DateTime形式のスペースでした。 %20に置き換えられ、すべて正常です。 – ETFairfax

答えて

4

まず、DateTimeパラメータは、であることはできません。これは値型です。第二に、あなたがこのような単純なタスクのためにあまりにも多くのコードを書いているすべての:

using (var client = new WebClient()) 
{ 
    var values = new NameValueCollection 
    { 
     { "myString", "Bonjour" }, 
     { "myDateTime", DateTime.Now.ToString("yyyy-MM-dd") }, 
    }; 
    byte[] result = client.UploadValues(url, values); 
    string strResult = Encoding.UTF8.GetString(result); 
} 

はまた、あなたはまさにこのパラメータ名を送信する必要がありますので、パラメータは、あなたのコントローラのアクションにmyDateTimeと呼ばれていることがわかります。

+0

Compact FrameworkでWebClientを使用できないため、DateTimeにnullが割り当てられているという問題があります。 – ETFairfax

+0

フォーマット文字列「yyyy-MM-dd」を使用していると思われます。乾杯。 – ETFairfax

1

私はあなたのPOSTDATA文字列が間違っていると思います。次のようになります。

string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString(); 

詳細:コントローラのアクションで引数に結合するASP.NET MVCのパラメータが掲示値の名前やクエリ文字列に一致します。

0

スペルミスですか?あなたは 'myDate'を投稿していますが、あなたのアクションメソッドは 'myDateTime'を予期しています。