从客户端向服务器发送信息时,我是在客户端还是在服务器端(或两者)执行规则?
When sending information from the client to the server, do I enforce rules on the client side or server side (or both)?
我的问题是什么是必要的and/or最佳实践。
假设,例如我需要从输入到我的控制器中的一些文本,并且该文本不能为空。
<form action="BaHumBug/Index" method="post" id="xmasTextForm">
<input name="xmasText" type="text" id="xmasTextInput" />
</form>
我是否在客户端执行关于没有空文本的规则
$('#xmasTextForm').submit(function(ev) {
{
if ($('#xmasTextForm').val().isWhiteSpace())
{
alert("Fill the input with something, dude!");
return false;
}
}
或者服务器端
[HttpPost]
public ActionResult Index (string xmasText)
{
if (xmasText.IsWhiteSpace())
{
// ....
}
还是为了两层保护我都做?还是选择取决于其他因素?
如前所述 - 参见 JavaScript: client-side vs. server-side validation - 两者各有利弊。但我会说它在服务器上是必不可少的。
至少在控制器上进行验证始终是一个好习惯,这样您就可以确保您的应用程序没有收到无效数据。
客户端的验证也很重要,因为当客户端以错误的方式获取表单时,您可以为客户提供良好的反馈。
应用 TDD(测试驱动开发方法)对代码和控制器的良好设计有很大帮助,如果您熟悉,可以访问此 link 以获取更多信息。
通过测试,您可以通过理解并充分考虑可能的输入案例来设计您的应用程序。
Its always good to have validations at client side as well as server side.
原因是如果有人从互联网上禁用 javascript options.In 这种情况下,如果服务器端没有验证,您的用例将失败。
You can use annotations [Required] attribute to make it mandatory field.
If JavaScript is enabled,and there is no user input in mandatory field,you will see control will not pass to controller action.
In Case JavaScript is disabled,control will pass to controller action with **ModelState.IsValid** value will be false.
Server side code should be like this:
[HttpPost]
public ActionResult Index (string xmasText)
{
if (ModelState.IsValid)//rather than check of whitespace
{
// ....
}
}
我的问题是什么是必要的and/or最佳实践。
假设,例如我需要从输入到我的控制器中的一些文本,并且该文本不能为空。
<form action="BaHumBug/Index" method="post" id="xmasTextForm">
<input name="xmasText" type="text" id="xmasTextInput" />
</form>
我是否在客户端执行关于没有空文本的规则
$('#xmasTextForm').submit(function(ev) {
{
if ($('#xmasTextForm').val().isWhiteSpace())
{
alert("Fill the input with something, dude!");
return false;
}
}
或者服务器端
[HttpPost]
public ActionResult Index (string xmasText)
{
if (xmasText.IsWhiteSpace())
{
// ....
}
还是为了两层保护我都做?还是选择取决于其他因素?
如前所述 - 参见 JavaScript: client-side vs. server-side validation - 两者各有利弊。但我会说它在服务器上是必不可少的。
至少在控制器上进行验证始终是一个好习惯,这样您就可以确保您的应用程序没有收到无效数据。
客户端的验证也很重要,因为当客户端以错误的方式获取表单时,您可以为客户提供良好的反馈。
应用 TDD(测试驱动开发方法)对代码和控制器的良好设计有很大帮助,如果您熟悉,可以访问此 link 以获取更多信息。
通过测试,您可以通过理解并充分考虑可能的输入案例来设计您的应用程序。
Its always good to have validations at client side as well as server side.
原因是如果有人从互联网上禁用 javascript options.In 这种情况下,如果服务器端没有验证,您的用例将失败。
You can use annotations [Required] attribute to make it mandatory field.
If JavaScript is enabled,and there is no user input in mandatory field,you will see control will not pass to controller action.
In Case JavaScript is disabled,control will pass to controller action with **ModelState.IsValid** value will be false.
Server side code should be like this:
[HttpPost]
public ActionResult Index (string xmasText)
{
if (ModelState.IsValid)//rather than check of whitespace
{
// ....
}
}