简体   繁体   中英

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?

@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.

I think that all you need in this example is set specific attribute on your password property. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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