【问题标题】:Do Ajax after MVC Validation在 MVC 验证之后执行 Ajax
【发布时间】:2013-11-21 12:24:21
【问题描述】:

我有一个表单,在这个表单中我有来自模型的字段。 该表单是来自引导程序的模态对话框。当我单击提交按钮时,所有字段都必须有效。这行得通! 现在,如果模型验证有效,我想关闭模式并刷新页面。只有代码首先执行 Ajax 调用,然后是 Controller 中的 ModelState.IsValid

阿贾克斯:

    $('#addAlertModal form').submit(function (e) {

        //TODO: if ModelState.IsValid in Controller
        refreshAlerts();
        closeAlertModal();
    });

有人知道我能做些什么吗?或者这不可能?

编辑:

或者是否可以在if中调用Ajax函数:

        @if (ViewData.ModelState.IsValid) {
            //Call here the functions
            refreshAlerts(); //Error: The name 'refreshAlerts' does not exist in the current context
        }

【问题讨论】:

    标签: javascript ajax asp.net-mvc twitter-bootstrap modal-dialog


    【解决方案1】:

    这样试试,

     $("#YourbuttonId").click(function () {
    
                           var validation = $("#FormId"); 
                            if (!validation.valid()) {
                                  return false;
                             }
                             else {
                                refreshAlerts();
                               closeAlertModal();
                              }
                         });
    

    【讨论】:

    • 那不行!我在模型中有要求,而不是在视图中!现在验证将始终为真。
    【解决方案2】:

    尝试在视图中使用ViewData.ModelState.IsValid

    $('#addAlertModal form').submit(function (e) {
    
        @if (ViewData.ModelState.IsValid)
        {
             refreshAlerts();
            closeAlertModal();
    
        }
    });
    

    【讨论】:

    • 好的,我现在知道@if (ViewData.ModelState.IsValid) 有效,但现在我不能调用 ajax 方法
    【解决方案3】:

    您为什么不使用事件,以便在您的验证正常时关闭页面并刷新。您需要使用触发器。

    http://api.jquery.com/category/events/ http://api.jquery.com/trigger/

    【讨论】:

    • 我不完全明白你的意思!可以让我看一下代码吗?
    【解决方案4】:

    我有:

    @using (Ajax.BeginForm("Index", "ManageAlert", FormMethod.Post, new AjaxOptions { UpdateTargetId = "addAlertModal", InsertionMode = InsertionMode.Replace, OnSuccess = "afterSubmit(data)"}))
    { ... }
    
    function afterSubmit(data) {
        if (data.success === true) {
            refreshAlerts();
            closeAlertModal();
        }
    }
    

    在模型中我返回:

    return Json(new { success = true });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2017-11-08
      • 2012-08-22
      • 2023-04-05
      • 2011-09-09
      相关资源
      最近更新 更多