So I have a UserDisplayModel with the default MembershipUser as a property, and I’m trying to pass the whole view model to the controller, but for some reason the MembershipUser property and likely the whole model gets lost.
I found this out because I get a No parameterless constructor defined for this object error unless I manually instantiate the MembershipUser inside the display model constructor). Meaning the second action (posted below) tried to make a new UserDisplayModel and errors because MembershipUser has no default constructor.
Here’s my code:
Model
public class UserDisplayModel
{
public MembershipUser User { get; set; }
public UserDisplayModel(string id)
{
this.User = Membership.GetUser(id);
}
}
Actions
public ActionResult Delete(string id)
{
UserDisplayModel model = new UserDisplayModel(id);
return PartialView("Delete", model);
}
[HttpPost]
public ActionResult Delete(UserDisplayModel model)
{
Membership.DeleteUser(model.User.UserName);
}
View
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcWebRole1.Models.UserDisplayModel>" %>
<p>Are you sure you want to delete the following user?</p>
<h2><%: Model.User.UserName%></h2>
<% using (Html.BeginForm()) { %>
<p>
<%: Html.HiddenFor(model => model.User.UserName)%>
<input type="submit" value="Delete" class="small alert button" />
<input type="button" value="Cancel" class="small secondary button cancel-action" />
</p>
<% } %>
Is it possible to have this work, or does asp.net just not like having models inside models? Or did I just miss something silly?
The error:
Is caused by
As
UserDisplayModelhas no parameterless constructor for MVC to instantiate. It only has the constructor:I would probably changed the method too look like:
Or to be a little more MVC