问题
I'm trying to use Validation in razor, but when I try to use the line
Validation.RequireFields("firstName", "lastName", "dateOfBirth");
visual studio tells me:
'System.Web.Helpers.Validation' is obsolete: '"Use System.Web.HttpRequest.Unvalidated instead."'
and
'System.Web.Helpers.Validation' does not contain a definition for 'RequireFields'
but the most up to date reference I can find is http://www.asp.net/web-pages/overview/more-resources/asp-net-web-pages-api-reference#Validation and I don't really see how Unvalidated is supposed to do what I want.
How do I do validation?
Thanks!
Here's my web.config in case it's relevant:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="WebRole2" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
回答1:
Do validation on your model with attributes:
public class MyModel
{
[Required][StringLength(100)]
public string FirstName {get;set;}
}
See this excellent blog post which explains it quite nicely. Also if the framework attributes don't fulfill your requirements, this library has a lot of extra attributes.
来源:https://stackoverflow.com/questions/24813224/validation-in-asp-net-web-pages-razor-deprecated