【问题标题】:Ajax.BeginForm return Json for messageAjax.BeginForm 返回 Json 消息
【发布时间】:2014-12-05 20:15:13
【问题描述】:

我正在使用 jquery unobtrusive ajax 和 MVC Ajax.Beginform() 通过 C# 服务器端验证表单。 我总是用自己替换表单。

一切正常,但我想知道:

假设我的表单正在触发“保存到数据库”操作并且该操作成功。表单中没有错误,所以我不想将表单发回客户端,而是在前端触发成功对话框的 JSON 消息。问题是表单替换总是在发生。当我从服务器取回 json 时,如何强制它不替换我的表单?

我想我要问的是:我怎么能不更新 div 而只做一些其他代码呢?

我知道 onSuccess,但它在 DIV 替换后触发,我想跳过替换。

【问题讨论】:

  • 如果你真的需要,我可以,但一切正常。我没有问题,只是一个问题:-)

标签: .net ajax asp.net-mvc unobtrusive-ajax


【解决方案1】:

您应该使用 jQuery ajax 来发布表单,而不是使用 Ajax.Beginform 来实现这种功能。 Ajax.BeginForm 的重点是发布表单并更新给定的目标。如果要返回部分视图或 JSON 对象,则应使用 jQuery 进行页面替换和成功对话框触发。

【讨论】:

    【解决方案2】:

    您可能必须实现自定义替换功能

    • 服务器端:

    1) 创建一个响应模型,该模型将包含您的响应状态以及相应的消息

    public class ReposnseModel
    {
        public bool isSuccess {get; set;}
        public string SuccessMessage {get;set;}
        public string ErrorMessage {get;set;}
    }
    

    2) 您的表单必须通过局部视图呈现,因此您只能返回其内容

    public ActionResult DoWork(Model model)
    {
    
    //if success:
    ...
    return Json(new ReposnseModel{isSuccess = true, SuccessMessage = "Success"});
    
    //if lets say model is not valid or some other error:
    return PartialView("YourPartialViewForm",model)
    
    }
    
    • 客户端

    使用类似这样的方式注册 Ajax.BeginForm onSuccess 回调:

      function Callback(data) {
        if (data != null) {
            if (data.isSuccess != undefined) { //means that the data is a serialized ReposnseModel and not a form content
                if (data.isSuccess) {                
                    alert(data.SuccessMessage);               
                }else
                {              
                    alert(data.ErrorMessage);
                }
            }
            else { //otherwise data is a form content, so it needs to replace the current content  
                $('#formContainer').html(data);
            }
         }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2011-07-17
      • 2017-07-16
      • 2023-03-25
      • 2017-09-28
      • 2012-10-21
      • 1970-01-01
      相关资源
      最近更新 更多