简体   繁体   English

如何使模型验证来自其他控制器的局部视图?

[英]how to make the model validate a partial view that comes from a different controller?

I've been trying to learn asp.net MVC coming from a webforms background and I believe I didn't get the idea of actions, controllers and their relation to partials very well... 我一直在尝试学习来自Webforms背景的asp.net MVC,但我认为我对动作,控制器及其与部件之间的关系了解得不是很好。

I have a _Layout.cshtml file that includes a _LoginPartial.cshtml (it's not the default code from Visual Studio, just the same name) and a Home/Index.cshtml file which includes the same partial (_LoginPartial) as well, here's the code for the partial: 我有一个_Layout.cshtml文件,其中包含_LoginPartial.cshtml (这不是Visual Studio中的默认代码,只是名称相同),还有一个Home / Index.cshtml文件,其中也包含相同的部分(_LoginPartial),这是代码对于部分:

@model LoginModel
@if (Request.IsAuthenticated) {
    @*<welcome text here>*@
} else {
    if ( Model.Layout == LoginLayout.Compact ) {
        @*<simple layout here>*@
    } else {
        <form method="post" action="~/Profile/Login">
            @Html.AntiForgeryToken()

            @Html.LabelFor(m => m.Email, "Email Field")
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)

            @Html.LabelFor(m => m.Password, "Password Field")
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)

            @Html.ValidationSummary()
        </form>
    }
}

so the _Layout.cshtml file includes the _LoginPartial.cshtml with the following code (no form tag inside _Layout.cshtml): 因此_Layout.cshtml文件包含具有以下代码的_LoginPartial.cshtml (_Layout.cshtml中没有表单标记):

@Html.Partial("_LoginPartial", new LoginModel())

and the Home/Index.cshtml includes the same partial with the following code (no form tag besides the one inside _LoginPartial either): 并且Home / Index.cshtml包含具有以下代码的相同部分(除了_LoginPartial中的一个,也没有表单标签):

@Html.Partial("_LoginPartial", new LoginModel() {
    Layout = LoginLayout.Full
})

so instead of using the default "AccountController" I decided to create a new one (PostController) to try, the partial above posts it's data successfully to ProfileController , but when the data is incorrect the ValidationMessage is always empty , here's the code to my controller: 因此而不是使用默认“的AccountController”我决定创建一个新的(PostController中)来尝试,部分上述职位是成功的数据ProfileController可 ,但是当数据是不正确的ValidationMessage总是空的 ,这里的代码,以我的控制器:

public class ProfileController : BaseController
{
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel form)
    {
        if (ModelState.IsValid)
        {
            //code to validate the user here
            if (userIsValid)
            {
                FormsAuthentication.SetAuthCookie(form.Email, false);
                return RedirectToAction("Index");
            }
        }

        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return RedirectToAction("Index", "Home");
    }
} 

as you can see, the partial is accessed via Home/Index.cshtml but its controller is located at Profile/Login, so when it redirects back to the Home/Index page no validation message is shown... 如您所见,该部分可通过Home / Index.cshtml访问,但其控制器位于Profile / Login中,因此当它重定向回Home / Index页面时,不会显示验证消息...

my question is : am I doing the right thing? 我的问题是 :我做对了吗? how can I show the ValidationMessage from my model? 如何显示模型中的ValidationMessage? if I'm not doing the right thing, how these actions and controllers are supposed to be structured to be true to the MVC model? 如果我做的事情不正确,那么应该如何构造这些动作和控制器以使其符合MVC模型?

and just for sake of completeness, here's my LoginModel class: 为了完整起见,这是我的LoginModel类:

public enum LoginLayout {
    Compact,
    Full
}
public class LoginModel
{
    public LoginLayout Layout { get; set; }

    [Required(ErrorMessage = "Please enter your e-mail")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please enter your password")]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

You are doing quite the right thing, but out the blue just like that, do you have the validation message for the Required annotations ? 您所做的事情是正确的,但是突然之间,您是否获得了Required批注的验证消息? Or is it just missing for the one you added to the model state ? 还是只是缺少您添加到模型状态中的那个? If it missing for all of them 如果所有的人都不见了

@Html.Partial("_LoginPartial", new LoginModel())

Might be the problem, have you tried @Html.EditorFor instead (edit: forgot to mention that you should then move your partial view _LoginPartial to the root editor template folder)? 可能是问题所在,您是否尝试过@Html.EditorFor (编辑:忘记提及您应该将_LoginPartial局部视图移至根编辑器模板文件夹)? You should also use that for the password and email btw. 您还应该使用该密码作为密码并发送电子邮件至btw。

In any case, the error added to the model state don't have a place for MVC to display, you will need something along the line of @Html.ValidationSummary(true) I think remember reading something about displaying only specific validation errors, let me see if I can dig that for you 无论如何,添加到模型状态的错误都没有MVC可以显示的地方,您将需要@Html.ValidationSummary(true)我想请记住阅读一些有关仅显示特定验证错误的内容,我看看我是否可以为您挖掘

EDIT: Just spotted that, use @using(@Html.BeginForm( as well instead of manually putting the form like that, it easier and more Razor friendly (you will be able to ajaxify that later on quite easily, which I would recommend for a logging form like that) 编辑:刚刚发现,使用@using(@Html.BeginForm(以及,而不是像这样手动放置表单,那样更容易,也更加Razor友好(您以后可以很容易地将其进行Ajaxize,我建议这样做)这样的日志记录形式)

EDIT 2: haHA Here is what I'm talking about, link , the answer here will allow you to display a specific model state error if it exist, but you'll need to give it a key when you add it to the model state 编辑2:哈哈这就是我在说的, 链接 ,这里的答案将允许您显示特定的模型状态错误(如果存在),但是将其添加到模型状态时需要给它一个键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM