Luc*_*elt 4 asp.net-core-2.0 razor-pages
我是Web开发的新手,所以我不知道如何在请求之间保持数据.
到目前为止这是我的网站:
根据titleId查询参数,GET请求中的API正在获取大象标题.当我按下登录时,正在运行模型验证,例如必须输入电子邮件和密码.但是,当返回错误页面时,大象文本为空,因为该值未持久存在.保留该值的最佳方法是什么,以便在返回POST错误时仍然可见?它是否必须包含在POST数据中?我不想再次请求API.
代码背后:
public class IndexModel : PageModel
{
private string apiTitle;
public string ApiTitle { get { return apiTitle; } set { apiTitle = value; } }
// Bind form values
[BindProperty]
public User user { get; set; }
public Task<IActionResult> OnGetAsync(string titleId)
{
if (!string.IsNullOrEmpty(titleId))
{
ApiTitle = await GetTitleFromApiAsync(titleId);
}
return Page();
}
public async Task<IActionResult> OnPostLoginAsync()
{
if (!IsLoginFormValid())
{
// When this is returned, for example if no password was entered,
// elephant title goes missing since apiTitle is null?
return Page();
}
var user = await LoginEmailAsync();
return RedirectToPage("/Profile");
}
}
Run Code Online (Sandbox Code Playgroud)
HTML:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<link rel="stylesheet" href="css/index.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<div class="login-page">
<span id="label_api_title">@Model.ApiTitle</span>
<div class="form">
<form class="login-form" method="post" asp-page-handler="Login">
<input type="text" placeholder="Email" asp-for="User.Email"/>
<span asp-validation-for="User.Email" class="text-danger"></span>
<input type="password" placeholder="Password" asp-for="User.Password1" />
<span asp-validation-for="User.Password1" class="text-danger"></span>
<button>login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
</div>
</div>
<script src="js/index.js"></script>
Run Code Online (Sandbox Code Playgroud)
是.你看到的是预期的行为.请记住,Http是无国籍的.您正在进行2个单独的http调用,一个用于GET,另一个用于POST.第二个电话不知道第一个电话是做什么的(甚至根本没有第一个电话!)
如果您想要ApiTitle在Post调用中读取属性值并将其返回到视图,则需要将其保留在某处,以便在http调用之间可用.但在您的情况下,您只需要在表单中包含它并让框架为您绑定它.
在您的情况下,您可以简单地使用公共属性(可设置和可获取).无需保留私有变量.使用BindProperty属性装饰属性,以便模型绑定器绑定此属性上的数据.
public class CreateModel : PageModel
{
[BindProperty]
public string ApiTitle { get; set; }
//Your existing code goes here
}
Run Code Online (Sandbox Code Playgroud)
现在在表单标记内,有一个输入隐藏元素ApiTitle.这样,当提交表单时,ApiTitle属性的值将在请求数据中发送.
<form class="login-form" method="post" asp-page-handler="Login">
<input type="hidden" asp-for="ApiTitle"/>
<input type="text" placeholder="Email" asp-for="User.Username"/>
<!--Your other existing form elements -->
<button>login</button>
</form>
Run Code Online (Sandbox Code Playgroud)
现在,在您的OnPostLoginAsync方法中,您可以根据需要读取ApiTitle值.返回页面时(验证失败时),UI将ApiTitle在span元素中显示属性值.
public async Task<IActionResult> OnPostLoginAsync()
{
var title = this.ApiTitle; // If you want to read this value
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("/Profile");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3235 次 |
| 最近记录: |