Kenzo
Kenzo

Reputation: 1837

How to convert formcollection to model ins ASP.NET MVC

I have a model class called ClientPackage and in my controller action method i receive a FormCollection from an ajax post call that i would like to convert it to the model class ClientPackage.

public class ClientPackage
    {
        public int DemandeId { get; set; }
        public string NumeroRequette { get; set; }
        public string NumeroModification { get; set; }
        public int CasId { get; set; }
        public string NumeroDossier { get; set; }
        public string NomPatient { get; set; }
        public string PrenomPatient { get; set; }
        public string NiveauPriorite { get; set; }
        public int NiveauPrioriteId { get; set; }
        public Unite UniteDepart { get; set; }
        public Unite UniteDestination { get; set; }
        public Demandeur DemandeurDepart { get; set; }
        public Demandeur DemandeurDestination { get; set; }
        public ConditionTransport ConditionTransport { get; set; }
        public Transport Transport { get; set; }

    }
[HttpPost]
        public string AjaxCall(FormCollection formData)
        {
            ClientPackage package = (ClientPackage)formData; //exception error


        }

I would appriciate any help

Upvotes: 0

Views: 341

Answers (2)

Lucas Lins Pereira
Lucas Lins Pereira

Reputation: 54

Instead of trying to convert you can use the FromForm attribute and receive your model as a parameter.

[HttpPost]
public ActionResult CreateClientPackage([FromForm] ClientPackage clientPackage)
{
...
}

Upvotes: 0

Rob Smitha
Rob Smitha

Reputation: 405

Here is how I post models with ajax.

<script>
function PostForm() {
        var model = $('#your_form_id').serialize();
        $.ajax({
            url: '/YourController/AjaxCall',
            type: 'POST',
            data: model,
            success: function (data) {


            },
            error: function (request, error) {
                console.log("Request: " + JSON.stringify(request));
            }
        });
    }
</script>

and in your controller.

[HttpPost]
        public string AjaxCall(ClientPackage model)
        {

             //no need to cast the model to a ClientPackage
             //ASP.NET mvc will do it for you as long as you send a serialized form that represents a ClientPackage object

        }

Hope this helps!

Upvotes: 0

Related Questions