The as
operator checks if the parameter is the specified type or descends from that type, and if so it returns a typed reference to it. Otherwise it returns null
. The type that you're casting from is never going to be either UserRoleViewModel
or anything that as
will recognize as casting from it, so you're just going to end up with an array of null
s, one for each property in the original JSON data.
The right way to handle this is to deserialize directly to the object type. If the JSON isn't formatted correctly for this you can use an intermediate type to deserialize to, then construct your UserRoleViewModel
from that.
Since you haven't provided any details for your model I'll make some stuff up.
Let's say you have a model that looks like this:
class UserRoleViewModel
{
public int UserID { get; set; }
public string UserName { get; set; }
public int RoleID { get; set; }
public string RoleName { get; set; }
}
On your form you have drop-downs for the User
and Role
, and the form data will only include the IDs for those two:
var rawJSON = "{\"UserID\":42,\"RoleID\":1}";
You can convert this to an instance of the view model directly:
var model = JsonConvert.DeserializeObject<UserRoleViewModel>(rawJSON);
The above produces an instance of UserRoleViewModel
with only the ID fields supplied. Any fields not found in the source JSON string will be left as default, so you'll need to be aware of what is and isn't useful in the model, which will depend on your HTML form configuration.
If instead you have a collection of view model data in the form data (looking something like [{"UserID":1,...},{"UserID:2,...}]
) then you can (and in fact must) deserialize the entire collection as an array or List<>
:
var models = JsonConvert.DeserializeObject<List<UserRoleViewModel>>(rawJSON);