对象作为动作控制器的参数? [英] Object as a parameter for an action controller?

查看:62
本文介绍了对象作为动作控制器的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动作控制器是否可以接受文字对象.例如,我有几种视图,我想将各种模型发布到单个控制器,然后可以确定传入的模型对象以进行进一步处理.

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 that can then determine the incoming model object for further processing.

模型样本:

public class Model1
{
   // properties, etc.
}

public class Model2
{
   // properties, etc.
}

public class Model3
{
   // properties, etc.
}

控制器样本:

[HttpPost]
public ActionResult ProcessModel(Object anyModel)
{
   // determine the model
   if((anyModel as Model1) != null)
   {
     var model1 = anyModel as Model1;
     // continue with code
   }
   else if((anyModel as Model2) != null)
   {
     var model2 = anyModel as Model2;
     // continue with code
   }
   // continue with model check, etc.       
}

我已经尝试过,但是我的控制器似乎没有拾取模型,因为我的对象参数保持为空.这可能吗?

I've tried, but my controller does not appear to be picking up the model as my object parameter remains empty. Is this possible?

推荐答案

具有

Have a quick read about how model binding works... The model binder (which takes whatever is posted to your Action and turns it into the anyModel parameter uses the type of the parameter to determine what to do.

由于类型为Object,因此无法执行任何操作.

Since the type is Object it can't do anything.

我的猜测(取决于您要实现的目标)是您可以有多个Action重载,每个重载都使用不同类型的Model作为参数,然后调用通用代码.

My guess (depending on what you're trying to achieve) is that you can have several Action overloads each with a different type of Model as the parameter which then call common code.

[HttpPost]
public ActionResult ProcessModel(Model1 anyModel){}

[HttpPost]
public ActionResult ProcessModel(Model2 anyModel){}

[HttpPost]
public ActionResult ProcessModel(Model3 anyModel){}

那表示采取一个动作需要很多不同的模型有点奇怪.您很有可能要做其他事情.

That said it's a bit odd to have one action which takes lots of different models. There's a good chance you're better off doing something else.

如果您说出自己要实现的目标,您的问题可能会得到更好的答案

Your question might gather a better answer if you say what you're trying to achieve

这篇关于对象作为动作控制器的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆