问题
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