我想在我的视图中使用RenderPartial两次与不同的模型相关联.问题是在两个模型中都有一些属性(昵称,密码).它们没有前缀,所以即使输出中的id或名称相等.现在,如果我有昵称或密码的模型错误,那么这两个字段都会突出显示.
主视图:
<div> <% Html.RenderPartial("Register",Model.RegisterModel); %> </div> <div> <% Html.RenderPartial("Login",Model.LoginModel); %> </div>
登录PartialView:
<% using (Html.BeginForm("Login","Member")) { %> <fieldset> <legend>Login</legend> <p> <%= Html.LabelFor(x => x.Nickname) %> <%= Html.TextBoxFor(x => x.Nickname) %> </p> <p> <%= Html.LabelFor(x => x.Password) %> <%= Html.PasswordFor(x => x.Password) %> </p> <input type="submit" value="Login" /> </fieldset> <% } %>
注册PartialView:
<% using (Html.BeginForm("Register","Member")) { %> <fieldset> <legend>Register</legend> <p> <%= Html.LabelFor(x => x.Nickname) %> <%= Html.TextBoxFor(x => x.Nickname) %> </p> <p> <%= Html.LabelFor(x => x.Email) %> <%= Html.TextBoxFor(x => x.Email) %> </p> <p> <%= Html.LabelFor(x => x.Password) %> <%= Html.PasswordFor(x => x.Password) %> </p> <p> <%= Html.LabelFor(x => x.PasswordRepeat) %> <%= Html.PasswordFor(x => x.PasswordRepeat) %> </p> <input type="submit" value="Register" /> </fieldset> <% } %>
我该怎么改?
解决方法
而不是使用Html.RenderPartial,您可以使用将处理前缀的
editor templates.
所以在你的主要观点:
<div> <%-- See below what does the second argument mean --%> <%= Html.EditorFor(x => x.RegisterModel,"RegisterModel") %> </div> <div> <%= Html.EditorFor(x => x.LoginModel,"LoginModel") %> </div>
然后创建一个文件夹Views / Shared / EditorTemplates / RegisterModel.ascx(该文件的名称在EditorFor Helper方法中使用).还要注意,这个部分应该强制类型为RegisterModel属性的类型:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Ns.Models.RegisterModel>" %> <% using (Html.BeginForm("Register","Member")) { %> <fieldset> <legend>Register</legend> <p> <%= Html.LabelFor(x => x.Nickname) %> <%= Html.TextBoxFor(x => x.Nickname) %> </p> <p> <%= Html.LabelFor(x => x.Email) %> <%= Html.TextBoxFor(x => x.Email) %> </p> <p> <%= Html.LabelFor(x => x.Password) %> <%= Html.PasswordFor(x => x.Password) %> </p> <p> <%= Html.LabelFor(x => x.PasswordRepeat) %> <%= Html.PasswordFor(x => x.PasswordRepeat) %> </p> <input type="submit" value="Register" /> </fieldset> <% } %>
您可以在Views / Shared / EditorTemplates / LoginModel.ascx中为登录模型定义不同的部分