Search code examples
asp.net-mvcpartial-viewsrazor-2

Partial View submit returns null


I'm trying to create a single view which allows the user to see the currently listed items using the index view model and then also allows the user to create a new item using a seperate create view model

So I've got two viewModels -IndexFunkyThingsViewModel -CreateFunkyThingViewModel

In essence I've got a main view:

@model IndexFunkyThingsViewModel
@foreach (var item in Model.FunkyThings)
{
/*Indexy stuff*/    
}

/*If create item*/
@if (Model.CreateFunkyThing)
{
@Html.Partial("_CreateFunkyThingPartial", new CreateFunkyThingViewModel());
}

Then in my partial view I have

@model CreateFunkyThingViewModel
@using (Html.BeginForm(MVC.FunkyThings.CreateFunkyThing(Model)))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Create FunkyThing</legend>
        @Html.EditorForModel();
        <p>
            <input type="submit" class="button green" value="CreateFunkyThing" />
        </p>
    </fieldset>
}

Finally in the controller I have:

[HttpPost]
public virtual ActionResult CreateFunkyThing(CreateFunkyThingViewModel createFunkyThingViewModel)
{
    ..
}

This all seems to compile happily and when I go to the view it works so far as displaying the create fields and such like. However when I then hit the submit button the controller receives no data. The ActionResult is called however in the debugger the createFunkyThingViewModel parameter is null when called by the submit button.

What am I doing wrong?


Solution

  • When posting to your controller, you're not sending the model down to it. Use this:

     @using (Html.BeginForm("CreateFunkyThing", "ControllerName", FormMethod.Post))
    

    then remove the p tags from around the button, and don't use anything with it.

    The paragraph tags have a tendency to group the button separately from a form even if they are in the same outer container.