Asp.net mvc 具有不同源和目标类型的UpdateModel
在我的操作中,我使用具有以下属性的Asp.net mvc 具有不同源和目标类型的UpdateModel,asp.net-mvc,Asp.net Mvc,在我的操作中,我使用具有以下属性的InsertPerson模型: pulbic class InsertPerson { [Required] public string Name{get;set;} } 我有一个DTO模型,它被传递到我的存储库: public class PersonDto { public int Id{get;set;} public string Name{get;set;} public string LastNam
InsertPerson
模型:
pulbic class InsertPerson
{
[Required]
public string Name{get;set;}
}
我有一个DTO模型,它被传递到我的存储库:
public class PersonDto
{
public int Id{get;set;}
public string Name{get;set;}
public string LastName{get;set;}
}
我的行动:
[HttpPost]
public ActionResult Create(InsertPerson insertPerson)
{
if(ModelState.IsValid){
var personDto = new PersonDto();
UpdateModel(personDto)
//UpdateModel(personDto, "insertPerson") I've tried this too
}
}
为什么它不工作(UpdateModel之后所有属性仍然为空)
有没有办法使用UpdateModel
更新我的personDto
我知道AutoMapper,但我认为在控制器中使用它很无聊
我的看法是:
@model Help_Desk.ViewModel.InsertPersonViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.InsertPerson.Name)
<button type="submit">Save</button>
}
好,现在我们看到问题了。缺少的信息是您使用的是视图模型,而视图模型创建的“容器”必须在UpdateModel中进行说明 所发生的事情是,UpdateModel试图在personDto对象中按字面意思更新“InsertPerson.Name”。既然那不存在,它就不起作用了
您可以通过指定
UpdateModel(personDto,“InsertPerson”)
来解决此问题。也许您想解释一下“不工作”的含义。对不起,问题是UpdateModel之后personDto的所有属性都为空。可能还提供了UpdateModel
..的代码?UpdateModel是System.Web.Mvc.Controller方法。insertPerson是否具有值?@murilokunze-应该可以工作。检查生成的html,查看输入标记的name属性,如果是“InsertPerson.name”,那么上面的代码应该可以工作。是的,name属性是正确的。不幸的是,它不起作用。@murilokunze-我在上面的代码中看到您使用的是“insertPerson”,而不是“insertPerson”。一般来说,这不应该区分大小写,但在使用UpdateModel时前缀可能是。非常感谢您的帮助。@murilokunze-所以前缀区分大小写?
public class InsertPersonViewModel
{
public InsertPerson InsertPerson{ get; set; }
}