如何在同一页面中使用两个表单在ASP.NET中。

huangapple go评论66阅读模式
英文:

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(&quot;api/[controller]&quot;, Name = &quot;Session&quot;)]
    [ApiController]
    public class SessionController : ControllerBase
    {
        
        public IActionResult LogOut()
        {
            //clear all session entries
            Request.Cookies.Keys.ToList().ForEach(cookie =&gt;
            {
                if(cookie == &quot;.AspNetCore.Session&quot;)
                {
                    Response.Cookies.Delete(cookie);        
                }

            });
           
            //redirect user to login page
            return RedirectToPage(&quot;/Index&quot;);     
        }
    
    }

The other controller that posts the bio to the database has its implementation details shown below

[Route(&quot;api/[controller]&quot;,Name= &quot;Bio&quot;)] 
public class BioController : ControllerBase{
  private Dbctx _dbctx;
  public IActionResult PostBio([FromForm] string bio) {
     var email = HttpContext.Session.GetString(&quot;email&quot;);
     _dbctx.Users.Where(x=&gt;x.Email== 
 email).FirstOrDefault().Bio = bio;
     return Ok(&quot;Bio updated successfully&quot;) ;
   } 
} 

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(&quot;LogOut&quot;, &quot;Session&quot;) ;
  } 
  //the second form has a text field that needs validation and a submit button 
  [Required(ErrorMessage=&quot;bio field cannot be empty&quot;] 
  [MaxLength(255)]
  [MinLength(30,ErrorMessage =&quot;bio should be at least 30 characters long&quot;)]
  public string Bio{get;set} 
} 

Second form looks like below

&lt;form method=&quot;post&quot;&gt;
&lt;textarea asp-for=&quot;Bio&quot; class=&quot;Form-control&quot; name=&quot;Bio*&gt;&lt;/textarea&gt;
&lt;input type=&quot;submit&quot; value=&quot;Add Bio&quot; class =&quot;btn btn-primary&quot; /&gt;
&lt;/form&gt;

答案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 = &quot;bio field cannot be empty&quot;)]
    [MaxLength(255)]
    [MinLength(5, ErrorMessage = &quot;bio should be at least 30 characters long&quot;)]
    public string Bio { get; set; }

    public void OnPostLogout()
    {
        Message = &quot;You Logged out&quot;;
    }

    public void OnPostRegister()
    {
        if (!ModelState.IsValid)
        {
            Message = &quot;Error&quot;;
        }
        else
        {
            Message = &quot;You Registered&quot;;
        }
    }
}

Named handler methods follow the same naming convention as standard handler methods On&lt;HTTP Method&gt;&lt;Name of handler method&gt;

&lt;form method=&quot;post&quot; asp-page-handler=&quot;Logout&quot;&gt;
    &lt;p&gt;Logout&lt;/p&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Logout&quot; /&gt;
&lt;/form&gt;
&lt;form method=&quot;post&quot; asp-page-handler=&quot;Register&quot;&gt;
    &lt;p&gt;Register&lt;/p&gt;
    &lt;textarea asp-for=&quot;Bio&quot; class=&quot;Form-control&quot;&gt;&lt;/textarea&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Register&quot; /&gt;
&lt;/form&gt;
&lt;p&gt;@Model.Message&lt;/p&gt;

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.

huangapple
  • 本文由 发表于 2023年7月3日 12:43:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定