2017-08-28 8 views
1

これは、RazorPagesのASP.NET Core 2.0 OnGetメソッドを使用しています。なぜこのコードは私にRequest.Formから無効なコンテンツタイプを与えていますか? (ASP.NETコア)

CSファイル:

using System; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Mvc.RazorPages; 

namespace CoreRazor2.Pages 
{ 
    public class IndexModel : PageModel 
    { 
    [BindProperty] 
    public int result { get; set; } 
    public void OnGet(string operationType) 
    { 
     string result; 
     switch (operationType) 
     { 
     case "+": 
      result = Request.Form["First"]; 
      break; 
     case "-": 
      result = "1"; 
      break; 
     case "/": 
      result = "2"; 
      break; 
     case "*": 
      result = "3"; 
      break; 
     } 

    } 
    } 
} 

CSHTMLファイル:最初のフォーム入力で値を入れて「+」ボタンを提出するをクリックすると

@page 
@model IndexModel 
@{ 
    ViewData["Title"] = "Calculator"; 
} 

<form method="GET"> 
<label>First Value: </label> 
<input name="First"/> 
<br/> 
<br/> 
<label>Second Value: </label> 
<input name="second"/> 
<br/> 
<br/> 
<input type="submit" name="operationType" value="+"/> 
<input type="submit" name="operationType" value="-"/> 
<input type="submit" name="operationType" value="*"/> 
<input type="submit" name="operationType" value="/"/> 
</form> 
@Model.result 

、プログラムはで次の例外がスローされますRequest.Form ["First"]:

Exception has occurred: CLR/System.InvalidOperationException 
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNetCore.Http.dll but was not handled in user code: 'Incorrect Content-Type: ' 
    at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm() 
    at Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest.get_Form() 
    at CoreRazor2.Pages.IndexModel.OnGet(String operationType) in c:\Users\Administrator\Desktop\CoreRazor2\Pages\Index.cshtml.cs:line 17 
    at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.VoidHandlerMethod.Execute(Object receiver, Object[] arguments) 
    at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.<InvokeHandlerMethodAsync>d__29.MoveNext() 

誰もが何故私を指摘しているのでしょうか?参考文献

答えて

3

GETベースのフォームは、フォームではなくURLを通じて値を渡します。 Request.QueryString["First"]を使用する必要があります。 Request.Formは、フォームをPOSTしているときにのみ機能します。しかし、あなたはRazor Pagesを使用しているので、すべての問題を解決し、モデルバインディングを使用することができます。

using System; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Mvc.RazorPages; 

namespace CoreRazor2.Pages 
{ 
    public class IndexModel : PageModel 
    { 
     public int Result { get; set; } 

     public void OnGet(string operationType, int first, int second) 
     { 
      switch (operationType) 
      { 
       case "+": 
        Result = first + second; 
        break; 
       case "-": 
        Result = first - second; 
        break; 
       case "/": 
        Result = first/second; 
        break; 
       case "*": 
        Result = first * second; 
        break; 
      } 

     } 
    } 
} 
関連する問題