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
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.