gpt4 book ai didi

asp.net-mvc - 在 ASP.Net MVC 中将同一 View 中的两个表单分开

转载 作者:行者123 更新时间:2023-12-04 17:29:08 24 4
gpt4 key购买 nike

我已在同一 View 中合并了创建帐户 View 和登录 View 。所以这是一个有两种形式的 View ,但是当我提交时它们会混合在一起。如果我尝试登录并显示以下错误:

Html.ValidationSummary()

两种形式都会出错。我开始将字段重命名为 loginPassword、createPassword,因为否则当我提交并且密码丢失时,它在两边都被标记为丢失。

将这两种形式分开以便它们可以在同一个 View /页面上独立工作的方法是什么?

最佳答案

啊,是的,我以前不得不这样做。我发现的方法是在 ViewData 中设置一个标志,详细说明发布了哪个表单,然后我为 ValidationSummary 创建了自己的扩展方法。

代码现在不在我身边,所以我现在会尽力为它做一些空气代码,这显然只是一个如何做的概念,所以请从表面上看。

首先,我将使用与 tvanfosson 建议的“EntryPageModel”相同的设置。

查看 - 备注 Html.MyValidationSummary

<% using(Html.BeginForm("NewAccount", "Account")) %>
<% { %>
<%= Html.MyValidationSummary("NewAccountForm") %>

<%= Html.TextBox("NewAccount.FirstName") %>
<%= Html.TextBox("NewAccount.LastName") %>
<%= Html.TextBox("NewAccount.Email") %>
<%= Html.Password("NewAccount.Password") %>
<%= Html.Password("NewAccount.ConfirmPassword") %>
<% } %>

<% using(Html.BeginForm("Login", "Account")) %>
<% { %>
<%= Html.MyValidationSummary("LoginForm") %>

<%= Html.TextBox("Login.Email") %>
<%= Html.Password("Login.Password") %>
<% } %>

Controller - 注意 ViewData["PostedForm"]
public class Account : Controller
{
private EntryPageModel _viewModel;

public ActionResult NewAccount(FormCollection formValues)
{
try
{
//binding and validation for _viewModel.NewAccount
}
catch
{
ViewData["PostedForm"] = "NewAccountForm";
return View("RegisterAndLogin", _viewModel);
}
}

public ActionResult Login(FormCollection formValues)
{
try
{
//binding and validation for _viewModel.Login
}
catch
{
ViewData["PostedForm"] = "LoginForm";
return View("RegisterAndLogin", _viewModel); //You'll want to pass in a model
}
}
}

自定义 html 扩展
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static string MyValidationSummary(this HtmlHelper html, string formName)
{
if (!string.IsNullOrEmpty(html.ViewData["PostedForm"])
&& (html.ViewData["PostedForm"] == formName))
{
return html.ValidationSummary();
}

return "";
}
}
}

HTH,
查尔斯

关于asp.net-mvc - 在 ASP.Net MVC 中将同一 View 中的两个表单分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/952844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com