Object as a parameter for an action controller?

前端 未结 3 418
走了就别回头了
走了就别回头了 2021-01-28 09:21

Is it possible for an action controller to accept a literal object. For example, I have several views in which I would like to post various models from to a single controller th

3条回答
  •  清酒与你
    2021-01-28 09:49

    Recently I faced the same issue and resolved it as below:

    Step 1: From javascript pass 2 parameter :

    First, pass model name as String for identification which model is coming

    Second, Pass data from javascript using JSON.stringify(data). where your data can be from Model1, Model2 , Model3 etc.

    Step2: In your controller:

    [HttpPost]
    public ActionResult ProcessModel(string modelName, string anyModel)
    {
       switch(modelName)  {
          case "Model1":
                 var modelValue= JsonDeserialize(anyModel);
                  // do something 
               break;
         case "Model2": 
                var modelValue= JsonDeserialize(anyModel); 
                // do something
               break;
        }
    }
    

    You Need One method like below:

    public T JsonDeserialize(string jsonModel){
    return JsonConvert.DeserializeObject(jsonModel, jsonSettings);
    }
    

    JsonConvert need namespace "Newtonsoft.Json".

    You also need to declare jsonSettings as below

             JsonSerializerSettings jsonSettings= new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            DefaultValueHandling = DefaultValueHandling.Ignore
        };
    

    This solution is kind of workaround. There is one more solution. you can check that also: How can I make a Controller Action take a dynamic parameter?

    Hope this helps.

提交回复
热议问题