如何使控制器操作采用动态参数? [英] How can I make a Controller Action take a dynamic parameter?
问题描述
我希望能够将任何序列化对象发布到操作方法并实例化发布类型的新对象,以便使用 TryUpdateModel
.他们没有在 QBasic 帮助文件中教我任何这些内容...如何根据发布的数据实例化未知类型?
I would like to be able to post any serialized object to an action method and instantiate a new object of the posted type in order to use TryUpdateModel
. They didn't teach me any of this stuff in the QBasic help file... How can I instantiate the unknown type based on the posted data?
如果有帮助,理论上我可以将类型的名称作为字符串包含在发布的数据中.我希望避免这种情况,因为我似乎需要类型的全名.
If it would help, I could theoretically include the name of the type as a string in the posted data. I was hoping to avoid that because it seemed like I would need the full name of the type.
public void Save(object/dynamic whatever, string typename) {
//Instantiate posted type
//TryUpdateModel
context.Entry(Thing).State = EntityState.Modified;
context.SaveChanges();
}
这是一个序列化对象的例子
Here is an example of a serialized object
Thing.Id=1&Thing.Name=blah&Thing.OptionID=1&Thing.ListItems.index=1&Thing.ListItems%5B1%5D.Id=1&Thing.ListItems%5B1%5D.Name=whatever&Thing.ListItems%5B1%5D.OptionID=2&Thing.ListItems%5B1%5D.ThingID=1&Thing.ListItems%5B1%5D.EntityState=16
来自提琴手
Thing.Id 1
Thing.Name blah
Thing.OptionID 1
Thing.ListItems.index 1
Thing.ListItems[1].Id 1
Thing.ListItems[1].Name whatever
Thing.ListItems[1].OptionID 2
Thing.ListItems[1].ThingID 1
Thing.ListItems[1].EntityState 16
推荐答案
您可以编写使用反射和 typeName
参数的自定义模型绑定器:
You could write a custom model binder which uses reflection and the typeName
parameter:
public class MyModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValue = bindingContext.ValueProvider.GetValue("typename");
if (typeValue == null)
{
throw new Exception("Impossible to instantiate a model. The "typeName" query string parameter was not provided.");
}
var type = Type.GetType(
(string)typeValue.ConvertTo(typeof(string)),
true
);
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
然后简单地:
[HttpPost]
public ActionResult Save([ModelBinder(typeof(MyModelBinder))] object model)
{
context.Entry(model).State = EntityState.Modified;
context.SaveChanges();
return View();
}
这篇关于如何使控制器操作采用动态参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!