试图更新控制器以避免验证模型 [英] Trying to update the model in controller to avoid validation

查看:113
本文介绍了试图更新控制器以避免验证模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的财产在我的模型:

  [显示(NAME =ActivityModel_FlashFile的ResourceType = typeof运算(App_GlobalResources.Models))]
[必填(ErrorMessageResourceName =ActivityModel_FlashFile_Required,ErrorMessageResourceType = typeof运算(App_GlobalResources.Models))]
公共字符串FlashFile {搞定;组; }

和在我的控制器我做的:

  ModelState.Remove(FlashFile);
 model.FlashFile =1;
 尝试
 {
    this.UpdateModel(模型);
 }
 赶上(异常前)
 {
    串allErrors =的string.join(,,ModelState.Values​​.SelectMany(V => v.Errors)。选择(E => e.ErrorMessage));
 ...

(当我们到了这个片段的开始FlashFile为空)。结果
然而,在这一点上 allErrors 是Flash文件是必需的。

(我把做这样的,从这里的想法)。

我如何避免验证FlashFile财产?


解决方案

  

我如何避免验证FlashFile财产?


通过使用适合于这种观点的要求视图模型。这是做的正确方法。如果不需要的 FlashFile 属性然后设计不具备要求属性,它为这个视图模型采取行动。

解决这个错误的方法是尝试重用您的域模型,然后排除你不从模型要绑定的属性:

 尝试
{
    this.UpdateModel(型号,NULL,NULL,新的[] {FlashFile});
    model.FlashFile =1;
}
赶上(异常前)
{
    字符串allErrors =的string.join(
        ,,
        ModelState.Values​​.SelectMany(V => v.Errors)。选择(E => e.ErrorMessage)
    );
    ...
}

I have the following property in my model:

[Display(Name = "ActivityModel_FlashFile", ResourceType = typeof(App_GlobalResources.Models))]
[Required(ErrorMessageResourceName = "ActivityModel_FlashFile_Required", ErrorMessageResourceType = typeof(App_GlobalResources.Models))]
public string FlashFile { get; set; }   

And in my controller I do:

 ModelState.Remove("FlashFile");
 model.FlashFile = "1";
 try
 {
    this.UpdateModel(model);
 }
 catch (Exception ex)
 {
    string allErrors=string.Join(",",ModelState.Values.SelectMany(v => v.Errors).Select(e=>e.ErrorMessage));
 ...

(FlashFile is empty when we get to the beginning of this snippet).
And yet, at this point allErrors is "Flash file is required".

(I took the idea of doing it like that from here).

How can I avoid validating the FlashFile property?

解决方案

How can I avoid validating the FlashFile property?

By using a view model that is adapted to the requirements of this view. That's the proper way to do it. If the FlashFile property is not required then design a view model which doesn't have the Required attribute on it for this action.

The wrong way to approach this is to attempt to reuse your domain models and then exclude the properties that you don't want from model binding:

try
{
    this.UpdateModel(model, null, null, new[] { "FlashFile" });
    model.FlashFile = "1";
}
catch (Exception ex)
{
    string allErrors = string.Join(
        ",", 
        ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)
    );
    ...
}

这篇关于试图更新控制器以避免验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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