Joe Defill
Joe Defill

Reputation: 499

Form POST is returning null model

I'm trying to save a model to my database via a form post. Here's how the model looks like:

public class CreditCard
{
    public CardDetails cardDetails { get; set; }
    public UserDetails userDetails { get; set; }
}

public class CardDetails
{
    public string CardNumber { get; set; }
}

public class UserDetails
{
    public string Name { get; set; }
}

Here's the view that displays the form, I'm using a view component for each object in CreditCard:

@model CreditCard

<form asp-controller="Card" asp-action="Save" method="post">
    <button type="submit" name="save" class="btn bg-blue"></button>

    @await Component.InvokeAsync("CardDetails", Model.cardDetails)
    @await Component.InvokeAsync("UserDetails", Model.userDetails)
</form>

CardDetails component:

@model CardDetails

<div class="form-group">
    @Html.EditorFor(model => model.CardNumber)
</div>

This works fine, i.e the components get the data from the database and the fields are populated just fine. However when I try to POST via the save button, it returns null. Here's the action (which does hit successfully, but the parameter has both cardDetails and userDetails as null:

public async Task<ActionResult> Save(CreditCard creditCard)
{
      // do stuff but creditCard.cardDetails and creditCard.userDetails are both null
}

Can someone figure out what's wrong here?

Upvotes: 0

Views: 58

Answers (1)

Viggo Lund&#233;n
Viggo Lund&#233;n

Reputation: 788

You're sending a different body to the server than it is set to consume.

Save takes CreditCard as an argument, but you're first sending a CardDetails object and then a UserDetails object.

You either need two different Save(), one taking CardDetails and one taking UserDetails or you construct the CreditCard object client-side before sending.

Upvotes: 2

Related Questions