开发者

TryValidate and manually set values in cotroller (ASP MVC 3)

开发者 https://www.devze.com 2023-04-10 18:23 出处:网络
I have a \"New user\" fo开发者_Python百科rm both for admins and for regular users. Both form use the RegisterModel

I have a "New user" fo开发者_Python百科rm both for admins and for regular users. Both form use the RegisterModel

public class RegisterModel
{
    [Required]
    public string Name { get; set; }

    public string Email { get; set; }

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

The difference is that on my front end "New user" page I want users to provide their own password. But in back end, I want the system to generate the password.

Since I use the same RegisterModel for both forms, I get a validateion error in the back end saying Password is required..

I thought, I could solve this by adding this to my controller:

    [HttpPost]
    public ActionResult New(RegisterModel model)
    {
        model.Password = Membership.GeneratePassword(6, 1);

        if (TryValidateModel(model))
        {
            // Do stuff
        }

        return View(model);
    }

But I still get the error message Password is required.. Why is this the issue when I do call TryValidate in my controller?

What would be best practice for this issue, create a separate RegisterModelBackEnd or are there any other solutions to this?


When updating model manually, you do not need to use it as parameter in Action. Also, use this overload that lets you specify only the properties on which binding will occur.

protected internal bool TryUpdateModel<TModel>(
    TModel model,
    string[] includeProperties
)
where TModel : class

So, the working code will be

[HttpPost]
public ActionResult New()
{
    RegisterModel model = new RegisterModel();
    model.Password = Membership.GeneratePassword(6, 1);

    if (TryValidateModel(model, new string[] {"Name", "Email"}))
    {
        // Do stuff
    }

    return View(model);
}

You can make this even simpler, using BindAttribute

[HttpPost]
public ActionResult New([Bind(Exlude="Password")]RegisterModel model)
{
    if(ModelState.IsValid)
    {
       model.Password = Membership.GeneratePassword(6, 1);
       // Do Stuff
    }

    return View(model);
}

And finally simplest and the best way

Define separate view models

0

精彩评论

暂无评论...
验证码 换一张
取 消