3 c# asp.net razor asp.net-core
这是使用RazorPages的ASP.NET Core 2.0 OnGet方法。
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
在第一个表单输入中输入值并单击“ +”提交按钮时,程序将在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()
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么或可以指出一些有用的文档吗?
Rom*_*kij 17
出于通用目的(作为日志记录),当您需要处理所有类型的 HttpRequests 时,请使用HttpRequest.HasFormContentType
示例代码:
if (request.HasFormContentType && request.Form != null && request.Form.Count() > 0)
{
dynamic form = new { };
foreach (var f in request.Form)
form[f.Key] = f.Value;
d.form = form;
}
Run Code Online (Sandbox Code Playgroud)
基于GET的表单通过URL而不是表单传递值。您需要使用Request.Query["First"]。Request.Form仅在发布表单时有效。但是,由于您使用的是Razor页面,因此您可以省去所有麻烦,而只需使用模型绑定即可:
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)