문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top