I'm trying to customize Identity (2.1) using MVC5 and EF6.1. I've added a CountryId to the Identity users table and a whole separate Country table (CountryId, CountryName) with a FK constraint on CountryId. I'm trying to do a drop down list that selects the users country if the user has already selected it in the past (from the CountryId in the users table). However, if it hasn't been selected, the value will be null.
The logic I'm trying to accomplish is this:
if (Model.Country.CountryName != null) {
@Html.DropDownListFor(m => m.Country, new SelectList(Model.Countries, "Value", "Text"), Model.Country.CountryName)<br />
} else {
@Html.DropDownListFor(m => m.Country, new SelectList(Model.Countries, "Value", "Text"), "Select a Country")<br />
}
If you remove the if else statement above (which doesn't work either), each DropDownListFor by itself works, except that the former throws a NullRefernceException when CountryName is null. The latter simply doesn't remember what the user chose in the past. Here is my controller:
var userId = User.Identity.GetUserId();
ApplicationUser user = await UserManager.FindByIdAsync(userId);
var model = new IndexViewModel
{
HasPassword = HasPassword(),
//PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
//TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
//Or we can write like this because of the user statement above.
//PhoneNumber = user.PhoneNumber,
//TwoFactor = user.TwoFactorEnabled,
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
Country = user.Country,
State = user.State,
City = user.City,
Countries = new SelectList(db.Countries, "CountryId", "CountryName")
};
return View(model);
If I use something like this in my controller model:
Countries = new SelectList(db.Countries, "CountryId", "CountryName", user.Country.CountryName)
Then it throws a NullReferenceException at the controller. I understand why this is happening, but for the life of me can't find an answer after half a day's search.
I'm just wondering if there is a clean way to handle the null value and therefore, pass a different default value if CountryId is null?
Any help is always much appreciated.
Edit: I forgot to mention the viewmodel. I basically added all this to the IndexViewModel (although I'm not sure if I need it all at this point):
public int CountryId { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public virtual Country Country { get; set; }
public virtual State State { get; set; }
public virtual City City { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }