Jakub Krason
Jakub Krason

Reputation: 1

MVC Mapping ViewModel only works with int

Here is a section of my controller code:

var userId = User.Identity.GetUserId();

var model = new IndexViewModel
{
    HasPassword = HasPassword(),
    PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
    TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
    Logins = await UserManager.GetLoginsAsync(userId),
    BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
    CC = db.Users.Single(x => x.Id == userId).CC
};

return View(model);

The following line only works when CC is of type int:

CC = db.Users.Single(x => x.Id == userId).CC

When CC is a string, I get the error below:

enter image description here

What am I doing wrong here?

Upvotes: 0

Views: 407

Answers (3)

Jakub Krason
Jakub Krason

Reputation: 1

I've worked it out. There was a glitch somewhere - I'm not sure where - CC was originally an int and then was changed to type string and after that it would not work. I have updated db and everything needed but it was still not working until complete pc reboot - after that is started working fine.

Upvotes: 0

Siraj Hussain
Siraj Hussain

Reputation: 874

If property always return number data then probably you will be need to convert into the int

CC = Int32.Parse(db.Users.Single(x => x.Id == userId).CC);

By the way if CC contains integer value then its data type also should be an integer.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65136

To be honest this really have nothing to do with MVC or models - it's just a basic C# problem.

You're trying to assign an int variable into something that only takes a string. If you want to convert an int into a string, call ToString:

CC = db.Users.Single(x => x.Id == userId).CC.ToString()

Upvotes: 2

Related Questions