gpt4 book ai didi

c# - Asp.NET MVC 模型绑定(bind) - 使用绑定(bind)参数属性为简单类型分配前缀

转载 作者:太空狗 更新时间:2023-10-30 00:59:23 24 4
gpt4 key购买 nike

我有一个 .net mvc 应用程序,它有一个接受用户注册帖子的 Controller 操作。我有以下 UI 字段:电子邮件地址、名字、姓氏、密码和确认密码。其中一些字段不属于模型对象(即确认密码不属于用户模型,仅属于密码)。我的注册表格与登录表格位于同一 View 中。所以我必须在同一个 View 上创建独立的表单,每个表单回发到不同的操作。

我想我可以为表单元素分配前缀以分隔注册和登录之间的类似字段。我遇到的问题是验证,如果发生错误,将重新加载 View ,显示验证消息,但电子邮件等字段(存在于登录和注册中)都将填充先前输入的地址。此外,我在登录和注册字段上方都有一个验证摘要。当注册过程中发生错误时,两个验证摘要都会填充错误消息。我认为为字段(register.fieldname 和 login.fieldname)分配前缀可能有助于解决这些问题。

因此,当注册操作处理帖子时,它不再查找注册表单字段的值,而是返回 null。以下是用于此操作的方法签名...

任何关于这里发生的事情的输入都会很棒。

谢谢杰里米

 public ActionResult Register([Bind(Prefix = "Register")] string emailAddress, [Bind(Prefix = "Register")] string firstName, [Bind(Prefix = "Register")] string LastName, [Bind(Prefix = "Register")] string password, [Bind(Prefix = "Register")] string confirmPassword)

下面是我的ui,代表注册表....

<h2>Create a New Account</h2>
<p>
Use the form below to create a new account.
</p>
<p>
Passwords are required to be a minimum of <%=Html.Encode(ViewData["PasswordLength"])%> characters in length.
</p>
<%= Html.ValidationSummary() %>

<% using (Html.BeginForm("register", "account")) { %>
<div>
<fieldset>
<legend>Account Information</legend>

<table>
<tr>
<td><label for="EmailAddress">Email Address:</label></td>
<td>
<%= Html.TextBox("Register.EmailAddress") %>
<%= Html.ValidationMessage("Register.EmailAddress")%>
</td>
</tr>
<tr>
<td><label for="FirstName">First Name</label></td>
<td>
<%= Html.TextBox("Register.FirstName")%>
<%= Html.ValidationMessage("Register.FirstName")%>
</td>
</tr>
<tr>
<td><label for="LastName">Last Name</label></td>
<td>
<%= Html.TextBox("Register.LastName")%>
<%= Html.ValidationMessage("Register.LastName")%>
</td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td>
<%= Html.Password("Register.password")%>
<%= Html.ValidationMessage("Register.password")%>
</td>
</tr>
<tr>
<td><label for="confirmPassword">Confirm password:</label></td>
<td>
<%= Html.Password("Register.confirmPassword")%>
<%= Html.ValidationMessage("Register.confirmPassword")%>
</td>
</tr>
<tr>
<td colspan="2" class="alignright">
<input type="submit" value="Register" />
</td>
</tr>
</table>
</fieldset>
</div>
<% } %>
</div>

最佳答案

我认为为了使用带有前缀的 [Bind],您需要使用复杂类型。您将相同的前缀与每个参数相关联,这不适用于 MVC 框架的处理方式。

您可以创建一个类型来处理表单发布:

public class RegistrationForm {
string EmailAddress {get;set;}
string FirstName {get;set;}
string LastName {get;set;}
string Password {get;set;}
string ConfirmPassword {get;set;}
}

然后您可以将您的签名更改为:

public ActionResult Register(RegistrationForm register) {
...
}

关于c# - Asp.NET MVC 模型绑定(bind) - 使用绑定(bind)参数属性为简单类型分配前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/592508/

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