I have a class User and then another Type UserSpecial with some special user properties. I pass it in razor to the partial method class to create the UserSpecial form which expects an object of type User Special but i get an error.
@model User
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@Html.Partial("../UserSpecial/_CreateOrEdit", Model.UserSpecial)
<p class="submit clear">
<input type="submit" value="Register" />
</p>
</fieldset>
}
</div>
Error i get -
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.User_AC9DED50C9495788046D6BFA3B90DDFC6AD2884157CF23C91FCB3B7A55F70B18', but this dictionary requires a model item of type 'UserSpecial'.
What am i doing wrong here?
From my controller i just pass the current User Object that i have stored in the session state.
Controller -
public ActionResult Register()
{
return View(userRepository.Current);
}
Here Current is of type "User"
Model -
public partial class User
{
public User()
{
}
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Sex { get; set; }
public System.DateTime CreateDate { get; set; }
public string Email { get; set; }
public string HomeTown { get; set; }
public short UserType { get; set; }
public virtual UserSpecial UserSpecial { get; set; }
}
Model Declaration for _CreateOrEdit is
@model UserSpecial
No idea what
userRepository.Current
is but it seems that it doesn't correctly/eagerly load theUserSpecial
property. Why don't you use view models? Why are you passing domain entity models to your views? That's bad practice. You should define view models that contain only the data that's required by your view and then in your controller action map between your domain models and the corresponding view model which will be passed to the view.The solution for this issue is pretty simple:
You should just use a wrapper class (view model) as Darin suggested.
So for example:
(entity domain model):
=> put it in a ViewModel (just a stupid wrapper) should result in this
Now, in the view, u should be able to access the "name" property by doing this
(notice you should not use @model.Name!)