gog
gog

Reputation: 12988

How to bind viewmodel on http post Action

Im trying to make this work but i cant figure out why its not working, on fiddler i get all the properties filled right, but on the action parameter it always come as null.

My ViewModel:

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

Index Action:

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

Index view:

 @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)
    } 

Post Action:

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

When i post the form i get all the objects as null. What im doing wrong here?

EDIT : _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>

Upvotes: 0

Views: 877

Answers (1)

py3r3str
py3r3str

Reputation: 1879

You 'send' to controller two different modelsModels.PerfilDTO and ModelsPaymentDto none of them is Models.PaymentViewModel.

Partial views should have same model as controller.

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

And you should pass same model to partial:

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

Upvotes: 1

Related Questions