Make HttpPost request to an action method in an ASP.NET MVC controller

NiK picture NiK · Dec 9, 2011 · Viewed 14.3k times · Source

I am trying to build a functionality where I need to a create a candidate's profile in our application. There are two steps/UI's to create a candidate's profile:

1 - Create template...where the user enters candidate's information.

2 - Preview template...where the user will be shown a preview of how their profile would look like once they add the profile to our system.

I have already created the views to support these UI's via a controller called "CandidateController" which contains few action methods:

1- [HttpGet] "Create" that returns a Create template.

[HttpGet]
public ViewResult Create()

2- [HttpPost] "Preview" that returns a Preview template.

 [HttpPost]
 public ActionResult Preview(ProfileViewModel viewModel)

Now what I need to implement is to have a button/link in the Create template that would call the action method [HttpPost] Preview in the controller.

Challenge I am also wondering if there is a way that the model binder would load the ViewModel object for me if am able to call the HttpPost Preview action method from the first create template.

I am looking for a suggestion/help to how to best achieve this kind a functionality.

Any help will be deeply appreciated.

Answer

Darin Dimitrov picture Darin Dimitrov · Dec 9, 2011

Challenge I am also wondering if there is a way that the model binder would load the ViewModel object for me if am able to call the HttpPost Preview action method from the first create template.

You could use either a standard form or an AJAX call to invoke the Preview POST action and pass all the property values of the view model then. All the values you pass in this request will be the values that will be bound by the default model binder. Here's an article explaining how the default model binder expects the parameters to be named for more complex structure such as lists and dictionaries.

Example with AJAX:

$.ajax({
    url: '@Url.Action("Preview")',
    type: 'POST',
    data: { Prop1: 'value 1', Prop2: 'value 2' },
    success: function(result) {
        // TODO: do something with the result returned from the POST action
    }
});

If you don't want to use AJAX you could use a standard form with hidden fields:

@using (Html.BeginForm())
{
    @Html.Hidden("Prop1", "value 1")
    @Html.Hidden("Prop2", "value 2")
    ...
    <button type="submit">Preview</button>
}