IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AJAX Discussion :

[AJAX] Comment passer une liste d'objets complexes en paramètre d'une requête ajax vers une action mvc ?


Sujet :

AJAX

  1. #1
    Membre habitué
    Inscrit en
    Novembre 2004
    Messages
    415
    Détails du profil
    Informations forums :
    Inscription : Novembre 2004
    Messages : 415
    Points : 138
    Points
    138
    Par défaut [AJAX] Comment passer une liste d'objets complexes en paramètre d'une requête ajax vers une action mvc ?
    Bonjour,
    J'ai le code suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    Mon index.cshtml :
    @using MasterManyGridViewMultipleFieldsKeyRazorMvc4.Models
    @model List<Master>
    <script type="text/javascript">
        $(function () {
        debugger;
            LoadingPanel.Show();
            $.ajax({
                type: "POST",
                url: '@Url.Action("IndexPartial")',
                data: @(Html.Raw(Json.Encode(Model))),
    //data: @(Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Json.Encode(Model)))),
                datatype: 'json',
                contentType:"application/json; charset=utf-8",
                success: function (response) {
                    $("#Container").html(response);
                    LoadingPanel.Hide();
                }
            });
        });
    </script>
     
     
    My IndexPartialView.cshtml :
    @model System.Collections.IEnumerable
    <br />
    use of "Model"
     
     
    My HomeController.cs :
    public class HomeController : Controller
        {
            public ActionResult Index()
            {
                //In my real project, I do some checks to allow the connection or not
                if (true)
                    Session["Rights"] = "OK";
                else
                    return new EmptyResult();
     
                return View("Index", DataProvider.GetMasters());
            }
     
            //public ActionResult IndexPartial(List<Master> m)
            [HttpPost]//[HttpGet]
            public ActionResult IndexPartial(string m)
            //public ActionResult IndexPartial()
            {
                var viewModel = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Master>>(m);
                //var viewModel = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Master>>(Request.QueryString[0]);
     
                return PartialView("IndexPartialView", /*m*/viewModel);
            }
    }
     
    My DataProvider.cs :
    public static IEnumerable GetMasters()
            {
                List<Master> list = new List<Master>();
                list.Add(new Master("Nancy", "Davolio", 20, "Felipe"));
                list.Add(new Master("Andrew", "Fuller", 30, "Don"));
                return list;
            }
     
    [Serializable]
    public class Master
        {
            string _firstName, _secondName, _fourthName;
            int _age;
     
            public Master()
            {
            }
            public Master(string first, string second, int age, string fourth)
            {
                this._firstName = first;
                this._secondName = second;
                this._age = age;
                this._fourthName = fourth;
            }
     
            public string FirstName
            {
                get { return _firstName; }
                set { _firstName = value; }
            }
     
            public string SecondName
            {
                get { return _secondName; }
                set { _secondName = value; }
            }
     
            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }
     
            public string FourthName
            {
                get { return _fourthName; }
                set { _fourthName = value; }
            }
        }
    Quand je regarde dans firebug au niveau de mon script, j'ai le contenu de data qui est :
    [{"FirstName":"Nancy","SecondName":"Davolio","Age":20,"FourthName":"Felipe"},{"FirstName":"Andrew","SecondName":"Fuller","Age":30,"FourthName":"Don"}
    Mais quand j'arrive dans mon action j'ai une exception qui est levée:
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext)
    at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
    at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
    at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
    at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
    at System.Web.Mvc.ControllerBase.get_ValueProvider()
    at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
    at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
    at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
    at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
    at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
    at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
    at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
    at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
    at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
    at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
    at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
    at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
    at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
    at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
    at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
    at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
    at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
    Quand j'essaye de mettre GET au lieu de POST dans le type de l'appel ajax, que je change [HttpPost] en [HttpGet], que je change la définition de la method de l'action en "public ActionResult IndexPartial()", alors j'ai Request.QueryString[0] qui vaut {undefined=undefined&undefined=undefined}... Si je continue l'execution de "var viewModel = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<Master>>(Request.QueryString[0]);", j'obtiens quasiement la même stacktrace, sauf que ça m'indique que l'erreur se situe au niveau de l'appel à à la méthode Derialize.
    Est-ce qeu vous pouvez me dire quel doit être la bonne syntaxe de mon appel ajax et de mon action mvc s'il vous plaît ?

  2. #2
    Membre habitué
    Inscrit en
    Novembre 2004
    Messages
    415
    Détails du profil
    Informations forums :
    Inscription : Novembre 2004
    Messages : 415
    Points : 138
    Points
    138
    Par défaut
    J'ai essayé de simplifier mon problème en passant seulement un objet, cela fonctionne de la manière suivante:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @model MasterManyGridViewMultipleFieldsKeyRazorMvc4.Models.Master
    <script type="text/javascript">
        $(function () {
        var m = {
            FirstName: "@Model.FirstName",
            SecondName: "@Model.SecondName",
            FourthName: "@Model.FourthName",
            Age: @Model.Age};
     
            $.ajax({
                type: "POST",
                url: '@Url.Action("IndexPartial")',
                data: JSON.stringify(m),
                datatype: 'json',
                contentType:"application/json; charset=utf-8",
                success: function (response) {
                    $("#Container").html(response);
                }
            });
        });
    </script>
     
    [HttpPost]
    public ActionResult IndexPartial(Master m)
    {
        return PartialView("IndexPartialView", m);
    }
    Du coup j'ai vu qu'il fallait passer un array, mais là je bloque, quelle est la syntaxe en javascript pour boucler sur ma liste de Master et créer un array qui contiendrait chacun des Master de la liste?

Discussions similaires

  1. Réponses: 1
    Dernier message: 25/04/2014, 11h32
  2. Passer une liste d'objets dans une méthode ajax
    Par AsPrO dans le forum ASP.NET Ajax
    Réponses: 4
    Dernier message: 01/03/2012, 11h28
  3. [AJAX] Récupérer une liste d'objet d'un flux RSS en JSON
    Par Tavarez59 dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 07/10/2007, 01h10
  4. Réponses: 7
    Dernier message: 30/05/2007, 16h17
  5. Réponses: 5
    Dernier message: 11/05/2006, 19h20

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo