The other day, I was testing some code that I had been writing for about a month. At some point early on in the coding, I realized that all of my views had some common "hidden" elements that I was saving for each screen in a tabbed environment, so, being the clever programmer I am, I decided to move these common elements into my _Layout.cshtml file. Of course, to do that, I also had to move my "@Html.BeginForm()" statement into the layout as well...
Ok... so fast-forward to my testing... suddenly, I realized that my client-side, jquery unobtrusive validation was gone. I had not tested this for quite some time because for the past couple of weeks, I had been testing other parts of the code and always entered valid data. So why did my client-side validation disappear?
Well, to make a long story short... After several hours of debugging and reverting code back to earlier days (and weeks), with no luck in recovering my validation, I found myself staring at a "view source" of my code and noticed that one of my "common" variables HAD the unobtrusive data elements, but my view did NOT.
After some googling, I discovered that what was happening is that the MVC engine processes the inner view FIRST, then the outer _Layout.cshtml view (the one that has the "BeginForm()" statement in it. Well, I found out that the MVC engine will NOT generate unobtrusive validation unless it first sees that it is in a BeginForm(0 construct, but since that construct is now in my _Layout, MVC does not think my View is in a form.
Now several programmers have various techniques to solve this, but the simplest solution that I found was to "fake" MVC into "thinking" there is a form in my view. In the Views folder, there is a file called _ViewStart.cshtml that tells all of your sub-views to use a particular layout (you can override this in your specific view), but the file simply has this code:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
All you need to do to "fake" your view into thinking there is a form is add this line:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
this.ViewContext.FormContext = new FormContext();
}
Now MVC will think you have a form and will generate the unobtrusive client-side validation attributes.
No comments:
Post a Comment