2

I need to send Model data along with Image so I am using FormData. As we can't pass model directly, I am using JSON.stringify.

How do I validate this Json string against Model (Same as we do ModelState validation)?

2
  • Why dont you send the image as blob, and add it to the model so that it gets validated during the ModelState validation? Commented Jan 30, 2019 at 6:29
  • @Hozikimaru Is it a better option than FormData for large images also? Commented Jan 30, 2019 at 17:25

1 Answer 1

3

yes you need to extract the model from the form data first e.g.

var request = HttpContext.Current.Request;
var model = new yourViewModel();
model.field1 = request.Form["field1"];
model.field2 = request.Form["field2"];
model.Document = request.Files["Document"];

ModelState.Clear(); 
this.Validate(model); 
if (ModelState.IsValid) {

}

Read more here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It worked. I am not sure if I can use ActionFilterAttribute in this scenario.
i guess you can check this [post stackoverflow.com/questions/10673649/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.