所以我有一个UserDisplayModel,默认的MembershipUser作为属性,我正在尝试将整个视图模型传递给控制器,但由于某种原因,MembershipUser属性和整个模型可能会丢失。
我发现了这一点,因为除非我在显示模型构造函数中手动实例化MembershipUser,否则会出现No parameterless constructor defined for this object
错误。这意味着第二个动作(下面发布)试图创建一个新的UserDisplayModel和错误,因为MembershipUser没有默认构造函数。
这是我的代码:
模型
public class UserDisplayModel
{
public MembershipUser User { get; set; }
public UserDisplayModel(string id)
{
this.User = Membership.GetUser(id);
}
}
操作
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);
}
查看
<%@ 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>
<% } %>
是否有可能让这项工作,或者asp.net不喜欢在模型中使用模型?或者我只是想念一些愚蠢的东西?
答案 0 :(得分:1)
看起来你真正需要的就是用户名。所以我会将模型更改为
public class UserDisplayModel
{
public string Username { get; set; }
}
答案 1 :(得分:0)
错误:
没有为此对象定义无参数构造函数
由
引起[HttpPost]
public ActionResult Delete(UserDisplayModel model)
{
Membership.DeleteUser(model.User.UserName);
}
由于UserDisplayModel
没有无参数构造函数供MVC实例化。它只有构造函数:
public UserDisplayModel(string id)
{
this.User = Membership.GetUser(id);
}
我可能会改变方法看起来像:
[HttpPost]
public ActionResult Delete(string userName)
{
Membership.DeleteUser(userName);
}
或者多一点MVC
public class DeleteUserModel
{
public DeleteUser User { get; set; }
public class DeleteUser
{
public string Username { get; set; }
}
}
[HttpPost]
public ActionResult Delete(DeleteUserModel model)
{
Membership.DeleteUser(model.User.UserName);
}