简体   繁体   中英

ASP.Net MVC Error Validation - How to display validation message when passing a custom view model to a view

I have been adding error and business validation to my app, and when I test using a view that was strongly typed to one model, let's say locations, I get the validation summary as well as the validation messages for each field that didn't pass, plus my css highlights the appropriate field as expected...

...when I try this with a view that's strongly typed to a custom view model, let's say I passed it location - so the user can enter a new one, as well as

IEnumerable<Location> locations

, so it will list out all of the existing locations below the new location form. When I do this I get the validation summary, but the message for each field is not displaying, nor is the css applying the * and the highlighting to each incorrect field.

I am using Linq to SQL, so I have added all of my validation as partial classes, so in this case all of the validation comes from the partial class location, which to my understanding will compile with the designer file that linq to sql created and add my business validation. Is this problem happening because I am not passing the view MyApp.Models.Location, and instead passing it MyApp.Models.MyCustomViewModel? if so, what's my best approach so that I can use just one form for create and list?

I was able to get this working - I changed the return value in my POST method to return

return View(new MyCustomViewModel(location) { });

instead of

return RedirectToAction(new MyCustomViewModel(location) { });

hope this helps if anyone stumbles across the same problem I did - which was my own misunderstanding of how View works differently than RedirectToAction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM