简体   繁体   English

从局部视图ASP.NET MVC C#调用ViewModel方法

[英]Calling viewmodel methods from partial view ASP.NET MVC C#

If I have a view model in this manner: 如果我以这种方式拥有视图模型:

public class ChangePasswordVM : IChangePasswordVM
{
    public bool IsValidPassword(string password)
    {
        return password.Length >= 7;
    }

    public void SetPassword(string password)
    {
        // set password
    }
}

Is it then possible from a partial view to call the IsValidPassword and SetPassword method? 然后可以从局部视图调用IsValidPassword和SetPassword方法吗?

@model ViewModels.IChangePasswordVM

Say that I have a @Html.BeginForm and on submit I check if it is a valid password, and if it is I call SetPassword method. 假设我有一个@ Html.BeginForm,并在提交时检查它是否为有效密码,以及是否调用SetPassword方法。

I think that all you need in this example is set specific attribute on your password property. 我认为在此示例中需要做的就是在password属性上设置特定的属性。 That's all. 就这样。 In your example I think you can use following attribute on Password Property: 在您的示例中,我认为您可以在“密码属性”上使用以下属性:

[MinLength(7, ErrorMessage="Password must have at least 7 characters")]
public string Password {get;set;}

ViewModel should be just a data which you want to bind - not a logic.So the password should be a property of your view model. ViewModel应该只是您要绑定的数据,而不是逻辑。因此,密码应该是您的视图模型的属性。

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

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