I have the following snippet.
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid) return View(model as LocalRegisterViewModel);
var user = new User
{
UserId = model.Username,
Password = null,
Email = model.Email,
AccType = model.AccountType
};
var modelAsLocalRegisterViewModel = model as LocalRegisterViewModel;
if (modelAsLocalRegisterViewModel != null)
user.Password = modelAsLocalRegisterViewModel.Password;
//...
}
The classes looks as follows.
public class RegisterViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public int AccountType { get; set; }
}
public interface IInternalPassword
{
string Password { get; set; }
string ConfirmPassword { get; set; }
}
public class LocalRegisterViewModel : RegisterViewModel, IInternalPassword
{
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
The LocalRegisterViewModel
is passed to the controller as follows from a cshtml
page.
@model LocalRegisterViewModel
@{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_LayoutAnonymous.cshtml";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
My problem is that, modelAsLocalRegisterViewModel
is null after the safe cast.
var modelAsLocalRegisterViewModel = model as LocalRegisterViewModel;
if (modelAsLocalRegisterViewModel != null)
user.Password = modelAsLocalRegisterViewModel.Password;
Can someone look into this and tell me why?
EDIT
Seems like my questioning style is bad. So let me clarify my exact intention as well. The Register
action I have written is intended to serve multiple ViewModels, each having some additional info. So what I have done is writing a parent which carries the common attributes and extending that to get the added attributes. For an instance, I pass an instance of a LocalRegisterViewModel
to the controller, so that it will first execute the common functionality and if the instance passed is of type LocalRegisterViewModel
if will carry out the extended functionality. That's why I need to check the passed RegisteredViewModel
is also of type LocalRegisterViewModel
.
EDIT 2 This is not trying to assign a base class instance to a derived class reference. It's a fact that following is completely valid in C#.
class Program
{
static void Test(Parent p)
{
var c = p as Child;
Console.WriteLine(c == null ? "Can't do it!" : "Can do it!");
Console.WriteLine(c.GetType().ToString());
}
static void Main(string[] args)
{
var c = new Child();
Test(c);
}
}
public class Parent
{
}
public class Child : Parent
{
}