我试图通过创建一个小型Web应用程序来了解Razor页面以及.Net Core的工作原理,并且我将继续研究如何处理表单中的按钮动作。我已经习惯了MVC类型的过程(从5年前我首次尝试Web应用程序时开始),在该过程中按钮具有可以从后面的代码访问的onClick操作,但似乎与Razor页面不同(除非我只是看不到它)。我有这样的基本形式
<form method="post">
<fieldset>
<input type="text" value="" placeholder="user name"/>
<input type="password" value="" placeholder="password"/>
<input type="button" value="Submit" id="submitButton"/>
</fieldset>
所以我想要实现的是,当按下按钮时,将调用.cs文件中的一个动作,该动作将执行几个不同的操作(例如调用API,获取结果,然后取决于结果路由到另一个页面)但是,即使我在按钮上添加了“ onClick”,也无法弄清楚如何将其连接到后面的代码。我已经看到了各种各样的答案,大多数使用模型和数据库,但是由于与我的做法不同,这些示例没有用。
我将尝试为您提供一个简单的例子。创建一个剃刀页面,并使用名称“ Test”。Test.cshtml文件应具有以下内容:
@page
@model WebApplication1.Pages.TestModel
<form method="post">
<fieldset>
<input asp-for="username" placeholder="user name" />
<span asp-validation-for="username" class="text-danger"></span>
<br />
<input asp-for="password" type="password" placeholder="password" />
<span asp-validation-for="password" class="text-danger"></span>
<br />
<input type="submit" value="Submit" id="submitButton" />
</fieldset>
</form>
Test.cshtml.cs应该具有以下内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
public class TestModel : PageModel
{
[BindProperty]
public string username { get; set; }
[BindProperty]
public string password { get; set; }
public void OnGet()
{
// you can initialize the values. for example I set the username
username = "test";
}
public IActionResult OnPost()
{
// do something with username and password
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("password", "Password is a required field.");
return Page();
}
// or you can redirect to another page
return RedirectToPage("./Index");
}
}
}
告诉我该示例是否需要其他说明。希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句