Zarch
Zarch

Reputation: 123

.NET Core MVC form passing model with null properties

I have a form that is suppose to pass my Encounter model to my CharacterController's CreateCharacter action method.

Here is the form:

<form asp-action="CreateCharacter" asp-controller="Character" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#character-container">
    <button class="btn btn-default" type="submit">Create Chracter</button>
</form>

Here's the controller method:

public ActionResult CreateCharacter(Encounter encounter)
{
    Character character = new Character { Encounter = encounter };
    return PartialView("Add", character);
}

All the properties of encounter are null when they shouldn't be. To clarify, Encounter is the model for the view that the form is in. Within this view, I use the Name property of Encounter and it works fine. When I pass the model to my controller, however, the Name property is now null.

I'm confused why this is happening because I have a very similar form elsewhere that passes a model fine.

Upvotes: 2

Views: 2645

Answers (1)

Nkosi
Nkosi

Reputation: 247183

No data is being submitted to the controller.

That form only has a submit button.

It is not sending any data as there are no input fields to represent the model to be sent.

If it sends nothing then the action will get a null value.

Ensure that there are values to be sent that match the properties on the model to be sent.

<form asp-action="CreateCharacter" asp-controller="Character" data-ajax="true" 
        data-ajax-mode="replace" data-ajax-update="#character-container">

    <input type="hidden" name="propertyName" value="propertyValue">

    <!--
    <input ... />
    <input ... />
    <input ... />
    -->     

    <button class="btn btn-default" type="submit">Create Chracter</button>
</form>

Upvotes: 3

Related Questions