Part 90 - Remote validation in mvc when javascript is disabled

本文介绍ASP.NET MVC中远程验证属性的工作原理及如何在禁用JavaScript时实现服务器端验证。探讨了两种方法:动态添加模型验证错误和创建自定义远程属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Please watch Part 89 from asp.net mvc tutorial, before proceeding.

Out of the box, Remote attribute only works when JavaScript is enabled. If the end user, disables JavaScript on his/her machine then the validation does not work. This is because RemoteAttribute requires JavaScript to make an asynchronous AJAX call to the server side validation method. As a result, the user will be able to submit the form, bypassing the validation in place. This why it is always important to have server side validation.

To make server side validation work, when JavaScript is disabled, there are 2 ways
1. Add model validation error dynamically in the controller action method
2. Create a custom remote attribute and override IsValid() method

In this video, we will discuss, adding model validation error dynamically in the controller action method. We will continue with the example, that we worked with in Part 89. Modify the Create action method that is decorated with [HttpPost] attribute as shown below.
[HttpPost]
public ActionResult Create(User user)
{
    // Check if the UserName already exists, and if it does, add Model validation error
    if (db.Users.Any(x => x.UserName == user.UserName))
    {
        ModelState.AddModelError("UserName""UserName already in use");
    }
    if (ModelState.IsValid)
    {
        db.Users.AddObject(user);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(user);
}

At this point, disable JavaScript in the browser, and test your application. Notice that, we don't get client side validation, but when you submit the form, server side validation still prevents the user from submitting the form, if there are validation errors.

However, delegating the responsibility of performing validation, to a controller action method violates separation of concerns within MVC. Ideally all validation logic should be in the Model. Using validation attributes in mvc models, should be the preferred method for validation. In our next video, we will discuss, creating a custom remote attribute and overriding IsValid() method. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值