如何在http post Action上绑定viewmodel

时间:2015-04-30 13:45:27

标签: c# asp.net-mvc

我试图让这个工作,但我无法弄清楚为什么它不工作,在提琴手我得到所有的属性填充正确,但在动作参数它总是为空。

我的ViewModel:

  public class PaymentViewModel
  {
    public UserDto UserModel { get; set; }
    public PaymentDto PaymentModel { get; set; }
  }

指数行动:

 public ActionResult Index()
    {
        var model = new PaymentViewModel
        {
            PaymentModel = new PaymentDto(),
            UserModel = new UserDto {P erfil = new PerfilDto() }
        };
        return View(model);
    }

索引视图:

 @model Models.PaymentViewModel

  @using (Html.BeginForm("Pay", "Payment", FormMethod.Post, new { @class = "col-lg-12 no-padding form-cadastro margin-top-20" }))
   {
        @Html.Partial("~/Views/User/_Register.cshtml", Model.UserModel.Perfil)
         @Html.Partial("_Payment", Model.PaymentModel)
    } 

发布行动:

     [HttpPost]
     public async Task<ActionResult> Pay(PaymentViewModel model)
     {
     }

当我发布表单时,我将所有对象都设为null。我在这里做错了什么?

编辑:_Register partial view

@model Models.PerfilDTO
<div class="row">   
<div class="form-group col-xs-12">
 @Html.LabelFor(m => m.Email)
 @Html.TextBoxFor(m => m.Email, new { @class = "form-control", id = "email", required = string.Empty })
</div>
<div class="form-group col-xs-12">        
    @Html.LabelFor(m => m.ConfirmEmail)
    <input type="email" class="form-control" id="confirmEmail"   name="ConfirmEmail" required>
</div>
<div class="form-group col-xs-12">
<div class="col-xs-12 col-sm-5 no-padding">
@Html.LabelFor(m => m.Password)
@Html.TextBoxFor(m => m.Password, new { @class = "form-control", id = "Password", required = string.Empty })
</div>        
</div>
</div>

1 个答案:

答案 0 :(得分:1)

您向管理员“发送”了两个不同的模型Models.PerfilDTOModelsPaymentDto,其中没有一个是Models.PaymentViewModel

部分视图应与控制器具有相同的模型。

@model Models.PaymentViewModel
...
@Html.TextBoxFor(m => m.UserModel.Perfil.Email, new { @class = "form-control", id = "email", required = string.Empty })
...

你应该将同一模型传递给partial:

...
@Html.Partial("~/Views/User/_Register.cshtml", Model)
@Html.Partial("_Payment", Model)
...