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)?
Asked
Active
Viewed 531 times
2

ArunPratap
- 4,816
- 7
- 25
- 43

Jeeten Parmar
- 5,568
- 15
- 62
- 111
-
Why dont you send the image as blob, and add it to the model so that it gets validated during the ModelState validation? – Hozikimaru Jan 30 '19 at 06:29
-
@Hozikimaru Is it a better option than `FormData` for large images also? – Jeeten Parmar Jan 30 '19 at 17:25
1 Answers
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

Shaheryar.Akram
- 722
- 10
- 19

Usama Kiyani
- 195
- 10
-
Thanks. It worked. I am not sure if I can use `ActionFilterAttribute` in this scenario. – Jeeten Parmar Jan 30 '19 at 17:21
-
i guess you can check this [post https://stackoverflow.com/questions/10673649/reading-form-data-in-actionfilterattribute] – Usama Kiyani Jan 31 '19 at 06:48