James
James

Reputation: 143

Set Property Not Working

I'm working on an ASP.NET MVC 5 (5.2.2) app in which I got a model:

public class MyModel{
    private String _Password;
    [Required]
    [StringLength(int.MaxValue, MinimumLength=6)]
    [DataType(DataType.Password)]
    public string Password {
        get
        {
            return Shell.ToolBox.Cryptography.GetMD5(_Password);
        }
        set {
            _Password = value; // This is not called
        }
    }
 }

The value of the _Password is always null, and when I change this property to an automatic type problem is solved. What is wrong, I used a break point, the set method is not even reached.

View:

<br />
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label" })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })

Upvotes: 0

Views: 372

Answers (1)

Austin Mullins
Austin Mullins

Reputation: 7427

@Blorgbeard revealed the solution. See the following model:

public class Dummy
{
    private string _field;

    [Required]
    [StringLength(int.MaxValue, MinimumLength=6)]
    [DataType(DataType.Password)]
    public string Field
    {
        get
        {
            if (_field == null)
            {
                throw new ArgumentNullException("Argh!");
            }

            return Utils.ByteArrayConverter.ByteArrayToString(
                MD5CryptoServiceProvider.Create(_field).Hash); 
        }
        set
        {
            _field = value;
        }
    }
}

I added the check for null (which throws an exception) to simulate what would happen if the MD5 hash function couldn't handle a null value argument. Sure enough, the page acts as if Field is always null, and the debug window logs the ArgumentNullException. In your case, we can still use the Shell.Toolbox version, but we just need to check for null first:

var pwd = _Password;
if (pwd == null)
{
    pwd = string.Empty;
}

return Shell.ToolBox.Cryptography.GetMD5(pwd);

Upvotes: 1

Related Questions