dazer
dazer

Reputation: 223

String in my .Net MVC model returns null but a List returns fine

For example in my model class

public class Dashboard
{
    public Dashboard(Account account)
    {
        AccountListName = new List<string>();
        AccountListName.Add(account.Name);

        string AccountName = account.Name;

    }
    public List<string> AccountListName { get; set; }

    public string AccountName { get; set; }

}

When I call the model in my controller.

var model = new DashBoard(account);

the model would contain the AccountListName properly but the AccountName would return null. Why does the AccountName returns null when I bind it to account.Name? Is there any weird interaction with the string type? And how do I fix this issue?

Upvotes: 0

Views: 176

Answers (3)

Jason Roell
Jason Roell

Reputation: 6809

Use:

this.AccountName = account.Name

instead of:

string AccountName = account.Name

You've accidentally redefined your AccountName to a local variable instead of assigning your property.

Upvotes: 1

Erik Noren
Erik Noren

Reputation: 4339

Because you've redefined a more local scope of AccountName within your constructor that never assigns the value to your property.

string AccountName = account.Name;

Just remove the string and you should be fine. I'm surprised the compiler isn't warning you.

Upvotes: 2

Matthew Beatty
Matthew Beatty

Reputation: 2812

You have declared AccountName a second time in the local scope of your function. You are setting this instead of the property of dashboard.

Upvotes: 2

Related Questions