【发布时间】:2014-11-30 08:16:30
【问题描述】:
这是我的模特
public class LoginModel
{
[UIHint("string")]
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
登录视图
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.UserName, new {id = "login-username", name="User name", placeholder = "Username" })
@Html.PasswordFor(m => m.Password, new { id = "login-password", type = "password", Class = "form-control", placeholder = "Password" })
<input type="submit" id="btn-login" class="btn btn-success pull-right" value="Sign In" />
}
字符串编辑器模板
字符串.cshtml
@model string
@{
string id = ViewBag.id;
string placeholder = ViewBag.placeholder;
string name = ViewBag.name;
<input value='@Model' id="@id" type="text" name="@name" class="form-control smheight" placeholder='@placeholder'>
}
控制器
[HttpPost]
public ActionResult Login(LoginModel user)
{
if (ModelState.IsValid)
{
if (user.Isvalid(user.UserName, user.Password))
{
FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Username and Password mismatch");
}
}
else
{
ModelState.AddModelError("", "Username and Password mismatch");
}
return View(user);
}
问题:1) 上述控制器动作中的 ModelState 在 EditorTemplate 中为假。 Otehrwise 工作正常。 2) @Html.EditorFor(m=> m.Username) 的 HTML 视图(没有字符串的 EditorTemplate)显示为
<input id="login-username" class="form-control" type="username" name="UserName" data-val-required="The Username field is required." data-val="true">
并且使用 EditorTemplate(下)HTML 不显示 数据- 属性
<input id="login-username" class="form-control" type="username" name="UserName">
我该如何解决这个问题?
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
为什么首先需要自定义编辑器模板?您向控制器发布了哪些值?
-
@VsevolodGoloviznin 我使用此编辑器模板只是为了将 '@class= form-control smheight' 属性应用于该 标记。
-
您可以通过简单地将@class 属性添加到您的定义中来做到这一点:
@Html.EditorFor(m => m.UserName, new {id = "login-username", name="User name", placeholder = "Username", @class="your-class" }) -
@VsevolodGoloviznin 那对我不起作用。类名替换为 html 中的“文本框单行”
标签: c# asp.net-mvc mvc-editor-templates modelstate