Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

asp.net mvc - How can I make a Controller Action take a dynamic parameter?

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

From Fiddler

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

and then simply:

[HttpPost]
public ActionResult Save([ModelBinder(typeof(MyModelBinder))] object model) 
{
    context.Entry(model).State = EntityState.Modified;
    context.SaveChanges();
    return View();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...