Trying to update the model in controller to avoid validation

你说的曾经没有我的故事 提交于 2019-12-25 05:23:20

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/12138552/trying-to-update-the-model-in-controller-to-avoid-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!