0

I have an Action like this:

Update([Bind(Prefix = "CurrentModel")] dynamic edited)

but when I use dynamic the ModelState.IsValid always returns true so it seems like there is no validation on the dynamic object? If not, how can I solve this?

Bartzilla
  • 2,768
  • 4
  • 28
  • 37
marcus
  • 9,616
  • 9
  • 58
  • 108

1 Answers1

2

There are two cases:

  1. You are using view models as action arguments in which case the default model binder automatically assigns the properties and sets possible errors to the model state:

    public ActionResult Update([Bind(Prefix = "CurrentModel")] EditViewModel edited)
    {
        if (ModelState.IsValid)
        {
    
        }
        ...
    }
    
  2. You are using some weak typing with either dynamic or FormCollection in which case the default model binder doesn't kick in and doesn't perform any validation at all as it is not capable of infering your real model type. In this case you need to manually call TryUpdateModel and indicate your model type:

    public ActionResult Update(dynamic edited)
    {
        var model = new MyViewModel();
        if (!TryUpdateModel(model, "CurrentModel"))
        {
            // The model was not valid
        }
        ...
    }
    

Conclusion: using dynamic as action argument in a controller action makes very little sense.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • @darin-dimitrov ok I see, the reason I use dynamic is because the Update method is a part of a generic editorial interface so I don't have a clue of which type the user is currently editing. The model is of type Dashboard.Web.Mvc.ViewModels.IDashboardViewModel which contains IPageModel CurrentModel { get; } and this is the object I'm editing. I agree that weak typing is not a great thing but in this case where the model is defined by another developer I think I need to do it this way or is there another way to have one view for editing models of various types? – marcus Mar 26 '11 at 14:45
  • @Marcus, another possibility would be to write a custom model binder for the `IDashboardViewModel` interface and then based on some request parameter (type?) return the proper implementation. Then your controller action could take the interface as argument. But there must be something in the request which indicates the actual type. – Darin Dimitrov Mar 26 '11 at 15:23
  • @darin-dimitrov, I ended up adding the current model as a parameter to the action like this Update(dynamic editorModel, dynamic model) then I use TryUpdateModel(model, "CurrentModel") as you suggested and it seems to work out great. Thanks for helping out! – marcus Mar 26 '11 at 15:50