weixin_33691817 2016-04-18 09:45 采纳率: 0%
浏览 127

mvc,ajax并重定向到页面

Imagine following situation: I want to let the user make a withdrawal. If it succeeds I should redirect him to action called Index of HomeController. If not (for instance, the balance of the account is less than the withdrawal sum), I want to display validation based error.

Now, I can't specify appriopriate validation rule while in the project phase (since it's not static rule like Required, the balance changes all the time), so I'm forced to make some runtime checking on user submit. That's okay, but now I've started wondering if in this case this is possible not to post back the page after sumbit.

Therefore, I've tried @using(Ajax.BeginForm(...){} and in the controller's appriopriate I could verify the user input. If this is incorrect, I could add the error to the model (general, or to some specified property) and return partial view including this error, not causing page post-back. This makes the same behavior as standard jQuery validation, yet of course it does not really stops post-back and just shows updated partial view.

The problem is if the input is correct- then using RedirectToAction("Index", "Home") makes generating the Index.cshtml as partial view too (so header and footer of my layout are doubled in this case) and that's understandable since it's stil AJAX request.

Now, my question is- first of all, is my considerations needed at all? I mean, I just thought not posting-back in this case could be more user-friendly. And if so, is there any other approach I could use in this case? I need fetching data from the given context (like database), then I can't just stop the postback on the client side.

  • 写回答

1条回答 默认 最新

  • weixin_33716941 2016-04-18 12:22
    关注

    You could use the Jquery Validate plugin to perform validation on the client side without actually interacting with the server at all. There are a couple of neat solutions in the link below:

    How can I validate that the max field is greater than the min field?

    The below is an adaptation of the first jsfiddle in the post linked above.

    $.validator.addMethod("greaterThan",
        function(value, max, min){
            return parseInt(value) > parseInt($(min).val());
        }, "Max must be greater than min"
    );
    
    $('#sales').validate({
      rules: {
        maxWithdrawal: {greaterThan: '#balance'}
      }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)