How to convert formcollection to model ins ASP.NET MVC

吃可爱长大的小学妹 提交于 2021-02-11 13:30:50

问题


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


回答1:


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!



来源:https://stackoverflow.com/questions/59956620/how-to-convert-formcollection-to-model-ins-asp-net-mvc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!