使用EditorTemplate,ModelState为false

时间:2014-11-30 08:16:30

标签: c# asp.net-mvc mvc-editor-templates modelstate

这是我的模特

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" />
}

EditorTemplate for string

string.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)使用EditorTemplate,上述控制器操作中的ModelState为false。 Otehrwise工作正常。 2)@ Html.EditorFor(m =&gt; 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">

我该如何解决这个问题?

任何帮助都将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

而不是使用EditorFor尝试使用带有class属性的TextBoxFor。

@Html.TextBoxFor(x => x.property, new { @class = "your-class" })

@using (Html.BeginForm())
{
     @Html.TextBoxFor(m => m.UserName, new {id = "login-username", name="User name", placeholder = "Username" })

     @Html.PasswordFor(m => m.Password, new { id = "login-password", placeholder = "Password", @class = "form-control" })

     <input type="submit" id="btn-login" class="btn btn-success pull-right" value="Sign In" />
}

您尝试使用&#39;类属性&#39;没有用,因为你忘了@ -character infront。 Razor认为它是关于一个C#类&#39;除非你用@来逃避它。因此,下次使用@class = "your-class"代替class = "your-class"。您也可以将type = "password"留在PasswordFor。