英文:
How to use two forms in the same page in ASP. NET
问题
我理解了,我将只翻译代码部分:
// 第一个控制器,用于处理退出登录
[Route("api/[controller]", Name = "Session")]
[ApiController]
public class SessionController : ControllerBase
{
public IActionResult LogOut()
{
// 清除所有会话条目
Request.Cookies.Keys.ToList().ForEach(cookie =>
{
if(cookie == ".AspNetCore.Session")
{
Response.Cookies.Delete(cookie);
}
});
// 重定向用户到登录页面
return RedirectToPage("/Index");
}
}
// 第二个控制器,用于将个人简介提交到数据库
[Route("api/[controller]", Name = "Bio")]
public class BioController : ControllerBase
{
private Dbctx _dbctx;
public IActionResult PostBio([FromForm] string bio)
{
var email = HttpContext.Session.GetString("email");
_dbctx.Users.Where(x=>x.Email==email).FirstOrDefault().Bio = bio;
return Ok("个人简介已成功更新");
}
}
// Dashboard 页面模型
public class DashboardModel : PageModel
{
public IActionResult OnPost()
{
// 对于第一个表单,正常退出登录
RedirectToAction("LogOut", "Session");
}
// 对于第二个表单,包含文本域输入和提交按钮
[Required(ErrorMessage="简介字段不能为空")]
[MaxLength(255)]
[MinLength(30, ErrorMessage ="简介至少应为30个字符")]
public string Bio { get; set; }
}
第二个表单的 HTML 代码如下:
<form method="post">
<textarea asp-for="Bio" class="Form-control" name="Bio"></textarea>
<input type="submit" value="添加简介" class="btn btn-primary" />
</form>
英文:
I have two buttons in my page where each button is nested inside a form. The first button in the first form is labeled Log Out and is used to end the session and log the current user out. The second button is for allowing the user to add a bio to his profile. Both forms use post method to submit data to the server. Whenever I submit the second form(which is supposed to post bio to database) , the server thinks it's the first form that I have submitted and redirects to the action method to log me out. I have two seperate controllers to handle the two forms separately. The controller that contains the method that logs me out has its implementation details shown below
[Route("api/[controller]", Name = "Session")]
[ApiController]
public class SessionController : ControllerBase
{
public IActionResult LogOut()
{
//clear all session entries
Request.Cookies.Keys.ToList().ForEach(cookie =>
{
if(cookie == ".AspNetCore.Session")
{
Response.Cookies.Delete(cookie);
}
});
//redirect user to login page
return RedirectToPage("/Index");
}
}
The other controller that posts the bio to the database has its implementation details shown below
[Route("api/[controller]",Name= "Bio")]
public class BioController : ControllerBase{
private Dbctx _dbctx;
public IActionResult PostBio([FromForm] string bio) {
var email = HttpContext.Session.GetString("email");
_dbctx.Users.Where(x=>x.Email==
email).FirstOrDefault().Bio = bio;
return Ok("Bio updated successfully") ;
}
}
Both forms are inside a page called Dashboard which has a model where I have defined the input field for the bio text area as a string property.
Is there a way to check which form submitted the request so each submission gets directed to the right controller. The first form contains no input fields except the submit button while the second form contains a text area input field and a submit button.
public class DashboardModel:PageModel{
public IActionResult OnPost() {
//works well for the first form and logs me out
RedirectToAction("LogOut", "Session") ;
}
//the second form has a text field that needs validation and a submit button
[Required(ErrorMessage="bio field cannot be empty"]
[MaxLength(255)]
[MinLength(30,ErrorMessage ="bio should be at least 30 characters long")]
public string Bio{get;set}
}
Second form looks like below
<form method="post">
<textarea asp-for="Bio" class="Form-control" name="Bio*></textarea>
<input type="submit" value="Add Bio" class ="btn btn-primary" />
</form>
答案1
得分: 1
我们想要使用 命名处理方法。现在我们可以在页面上有多个表单。
public class IndexModel : PageModel
{
public string Message { get; private set; }
[BindProperty]
[Required(ErrorMessage = "bio字段不能为空")]
[MaxLength(255)]
[MinLength(5, ErrorMessage = "bio应至少包含30个字符")]
public string Bio { get; set; }
public void OnPostLogout()
{
Message = "您已注销";
}
public void OnPostRegister()
{
if (!ModelState.IsValid)
{
Message = "错误";
}
else
{
Message = "您已注册";
}
}
}
命名处理方法遵循标准处理方法的相同命名约定 On<HTTP方法><处理方法名称>
<form method="post" asp-page-handler="Logout">
<p>注销</p>
<input type="submit" value="注销" />
</form>
<form method="post" asp-page-handler="Register">
<p>注册</p>
<textarea asp-for="Bio" class="Form-control"></textarea>
<input type="submit" value="注册" />
</form>
<p>@Model.Message</p>
处理方法的名称分配给了表单标签的 asp-page-handler
属性。
为了确保字段不为空,Bio
属性将被装饰上 BindProperty
属性。如果没有此属性,该属性将不参与模型绑定。
ModelState
有一个名为 IsValid
的属性,如果存在任何错误,它将返回 false。
英文:
We want to use named handler methods. Now we can have a page with multiple forms in it.
public class IndexModel : PageModel
{
public string Message { get; private set; }
[BindProperty]
[Required(ErrorMessage = "bio field cannot be empty")]
[MaxLength(255)]
[MinLength(5, ErrorMessage = "bio should be at least 30 characters long")]
public string Bio { get; set; }
public void OnPostLogout()
{
Message = "You Logged out";
}
public void OnPostRegister()
{
if (!ModelState.IsValid)
{
Message = "Error";
}
else
{
Message = "You Registered";
}
}
}
Named handler methods follow the same naming convention as standard handler methods On<HTTP Method><Name of handler method>
<form method="post" asp-page-handler="Logout">
<p>Logout</p>
<input type="submit" value="Logout" />
</form>
<form method="post" asp-page-handler="Register">
<p>Register</p>
<textarea asp-for="Bio" class="Form-control"></textarea>
<input type="submit" value="Register" />
</form>
<p>@Model.Message</p>
The name of the handler method is assigned to the asp-page-handler
attribute of the form tag.
To make sure the field is not empty, the Bio
property will be decorated with the BindProperty
attribute. Without this attribute, the property will not take part in model binding.
ModelState
has a property called IsValid
that returns false if there are any errors.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论