0

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

一切正常,但我想知道:

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

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

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

4

2 回答 2

1

You should jQuery ajax to post the form instead of Ajax.Beginform for this kind of functionality. The point of Ajax.BeginForm is to post the form and update a given target. If you want to return either a partial view or a JSON object, you should do the page replacing and success dialog triggering with jQuery.

于 2014-12-05T20:22:25.267 回答
0

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

  • 服务器端:

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);
        }
     }
  }
于 2014-12-05T20:52:59.807 回答