【问题标题】:MVC Nested View Model with Validation带有验证的 MVC 嵌套视图模型
【发布时间】:2015-07-03 13:19:14
【问题描述】:

我正在尝试将登录和注册表单放在同一个视图中。我做了其他问题中建议的所有事情,但我的问题仍然没有解决。

这是我的父视图authentication.cshtml:

@model Eriene.Mvc.Models.AccountVM
    <div class="row">
        <div class="col-md-6">
            @Html.Partial("_Login", Model.Login ?? new Eriene.Mvc.Models.LoginVM())
        </div>
        <div class="col-md-6">
            @Html.Partial("_Register", Model.Register  ?? new Eriene.Mvc.Models.RegisterVM())
        </div>
    </div>

在我的部分中,我使用这样的形式:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @id = "login-form", @role = "form", @class = "login-form cf-style-1" }))

其中一个动作是这样的:

[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterVM registerVM)
{
    if (ModelState.IsValid)
    {
        User user = new Data.User();
        user.Email = registerVM.Email;
        user.ActivationCode = Guid.NewGuid().ToString();
        user.FirstName = registerVM.FirstName;
        user.LastName = registerVM.LastName;
        user.Password = PasswordHelper.CreateHash(registerVM.Password);
        return RedirectToAction("Index", "Home");
    }

    return View("Authentication", new AccountVM() { Register = registerVM });
}

以下是我正在使用的模型:

public class AccountVM
{
    public LoginVM Login { get; set; }
    public RegisterVM Register { get; set; }
}

public class RegisterVM
{
    [Required]
    public string Email { get; set; }

    [Required]
    public string FirstName { get; internal set; }

    [Required]
    public string LastName { get; internal set; }

    [Required]
    public string Password { get; internal set; }

    [Compare]
    public string PasswordRetype { get; internal set; }
}

public class LoginVM
{
    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public bool RememberMe { get; set; }
}

在action registerVM的Email属性有值,其他的都是nullModelState.IsValidfalse。 我究竟做错了什么?

【问题讨论】:

    标签: c# .net asp.net-mvc razor asp.net-mvc-validation


    【解决方案1】:

    您的属性未绑定,因为它们没有公共设置器(仅限内部),这意味着 DefaultModelBinder 无法设置它们(因此它们是 null 并且由于 [Required] 属性而无效。更改

    public string FirstName { get; internal set; }
    

    public string FirstName { get; set; }
    

    对于所有其他带有内部设置器的属性也是如此。

    【讨论】:

    • 天哪!我通过重构生成了该属性,我不知道它们是内部的。对不起这种废话。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2015-08-17
    • 2014-06-30
    • 2010-11-18
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多