Search code examples
formsasp.net-mvc-3child-actions

ASP.NET MVC3 Html.Action containing a form


I have a pod on my page that contains a form.

I have used this pod in a similar way to the following:

@Html.Action("Pod","Home")

There is some business rule checking in the Pod's HttpPost action which handles the form post. If this business rule fails, I add an error to the model state.

The problem is, that when the business rule fails to validate. I return a View from the pod action, which shows just the pod on a blank page.

How can I correctly reuse a form like this and still have server side validation of this business rule (requires a db hit to validate)?


Solution

  • One possibility is to AJAXify the form in the Pod partial:

    <div id="pod">
        @Html.Action("Pod","Home")
    </div>
    

    and inside Pod.cshtml:

    @using (Html.BeginForm("Pod", "Home", FormMethod.Post, new { id = "podForm" }))
    {
        ...
    }
    

    finally AJAXify it:

    $(function() {
        $('#podForm').submit(function() {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function(result) {
                    $('#pod').html(result);
                }
            });
        });
    });
    

    The last thing to make sure is that the POST action returns the Pod.cshtml as a partial view. Two possibilities:

    [HttpPost]
    public ActionResult Pod(PodViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return PartialView(model);
        }
        ...
    }
    

    or in the Pod.cshtml partial:

    @{
        Layout = null;
    }