Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC3 Remove ModelState Errors

I've got a situation where I'm uploading an image the user has selected from his local file system. My Form in my view, basically has two submit buttons. One is used to Submit the form normally, and all validation executes. The 2nd is only for uploading the image, in which case I don't want to validate yet.

I managed to turn off Client Side validation by giving my 'Upload Image' submit button an a class value of "style-name cancel" , so

<input type="submit" name="UploadImageButton" value="Upload Image" class="style-name cancel" /> 

Now, when I post back, my model has a property UploadImageButton, when this button is clicked, it populates this property (Name of the input matches the Property). This way, I know whether the form was submitted by my true Submit button or by the UploadImageButton.

My question is this... How can I turn off ServerSide validation? I don't want the Validation Summary info showing up when the user clicks this button. I know you can add custom model errors using this

ModelState.AddModelError("{key}", "{error msg}");

I'm looking for a means to Remove Model Errors. Is this possible?

EDIT:

Here is what I came up with:

foreach (var key in ModelState.Keys.ToList().Where(key => ModelState.ContainsKey(key))) {
     //ModelState.Remove(key); //This was my solution before
     ModelState[key].Errors.Clear(); //This is my new solution. Thanks bbak
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can remove model errors by doing something like this:

if (ModelState.ContainsKey("{key}"))
    ModelState["{key}"].Errors.Clear();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...