asp.net mvc json打开对话框问题 [英] asp.net mvc json open dialog box problem

查看:105
本文介绍了asp.net mvc json打开对话框问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 function postForm()  

{

 $.ajax({ 

     type: "POST",  

     data: $("#myForm").serialize(),  

     dataType: "json",

     url: '<%= Url.Action("JSONRequest","Home") %>',


     success: function(result)  
     {  
         window.alert(result.name);  
     },                  
     error : function()  
     {  
         window.alert('error');  
     }  
 });  

}

 Html.BeginForm("JSONRequest", "Home", FormMethod.Post, new { id = "myForm" });
 Html.TextBox("mazhar")  
 <input type="submit" onclick="postForm" />  
 Html.EndForm();



 public ActionResult JSONRequest(FormCollection form)
    {

        string a = form["mazhar"];
        var data = new { name = "aaaa", Success = "Record is Succesfully Saved", ErrorMessages = "abc" };
        return Json(data);  
    }

好的,问题是运行此代码要求保存文件后,对话框将打开. 有人可以告诉我如何解决此问题吗?为什么这个盒子会来呢?

Ok the problem is that the dialog box is opening after running this code which is asking to save file. Can someone tell me how to resolve this issue? Why does this box comes afterall?

推荐答案

您需要通过在按钮onclick处理程序内返回false来取消默认的表单提交:

You need to cancel the default form submission by returning false inside the button onclick handler:

<input type="submit" onclick="postForm(); return false;" />

话虽如此,我建议您一个更好的解决方案.使用 jquery.form 插件,该插件可以使HTML表单无效.这样,可以简化代码中的许多重复操作:

That being said, I would suggest you a better solution. Use the jquery.form plugin which enables you to ajaxify an HTML form. This way much of the duplication in your code could be simplified:

Html.BeginForm("JSONRequest", "Home", FormMethod.Post, new { id = "myForm" });
    Html.TextBox("mazhar")  
    <input type="submit" value="OK" />  
Html.EndForm();

在javascript中:

And in javascript:

$(function() { 
    $('#myForm').ajaxForm({
        success: function(result) {  
            window.alert(result.name);  
        },                  
        error : function() {  
            window.alert('error');  
        }  
    }); 
});

通过这种方式,您不再需要指定url,方法,手动序列化表单字段等.您也不需要使用JavaScript函数对HTML标记进行污染.这是不引人注目的javascript.这种方法的另一个优点是,由于不再依赖服务器端代码(<%= Url.Action("JSONRequest","Home") %>),现在您将能够将此JavaScript外部化为单独的静态.js文件,并且您将受益于减少带宽和缓存静态资源

This way you no longer need to specify url, method, manually serialize form fields, etc... You also don't need to pollute your HTML markup with javascript functions. This is unobtrusive javascript. Another advantage of this approach is that now you will be able to externalize this javascript into a separate static .js file as it no longer relies on server side code (<%= Url.Action("JSONRequest","Home") %>) and this you will benefit from reducing the bandwidth and caching static resources.

这篇关于asp.net mvc json打开对话框问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆