我怎样才能保持MVC JQuery Ajax POSTs DRY?

时间:2011-06-13 14:24:57

标签: asp.net-mvc ajax jquery

我正在使用Ajax将更新发布到服务器:

$("#my-check-box").change(function () {

         var value = $(this).attr("checked");
         var url = '<%: Url.Routes().MyAction() %>';
         $.ajaxSetup({ cache: false });
         $.post(url, { **myActionParameterName**: value }, function (data) {

             if (data.result != "success") {
                 alert(data.error);
             }

         });


     });

我不想在客户端编写参数名称(如果它发生了变化),但有没有办法避免这样做?

3 个答案:

答案 0 :(得分:3)

简单回答:不。在一天结束时,您的AJAX需要知道以某种方式调用参数。

你所谈论的是抽象,而不是“不要重复自己”的策略。 DRY表示“不要多次重复逻辑”,而不是“不要引用变量”。如果是这种情况,您将无法对变量或参数进行任何类型的引用,因为您在技术上重复了变量的名称。

您将不得不引用某些内容,并且一旦客户端和服务器端一次引用某些内容。你可以将它抽象成其他东西,当然,但最终只能引用你的动作参数并且不用担心它。

重构无论如何都会涉及一个简单的查找/替换,在任何抽象下都不会改变。

现在,如果您多次引用该JSON对象或在JavaScript中多次奇怪地构建它,那么当DRY发挥作用时,您应该创建一个方法,您可以传入数据来构建它。 / p>

答案 1 :(得分:1)

我建议使用jQuery.extend()功能来简化调用并创建一个javascript api。查看check out this video from MVC Conf

我使用像这样的标准ajax调用

//A standard ajax api call that takes in a set of options
//This uses the jQuery extend method to merge the supplied options with a set of defaults
(function ($) {
    $.apiCall = function (options) {
        var config = $.extend({
            type: 'GET',
            data: {},
            contentType: 'application/x-www-form-urlencoded',
            success: function () { },
            error: function () { }
        }, options);

        $.ajax({
            type: config.type,
            url: config.url,
            contentType: config.contentType,
            data: config.data,
            success: function (result) {
                config.success(result);
            },
            error: function (result) {
                config.error(result);
                flashError('An error occured during the operation');
                //Okay, so this last bit is kindof a problem. Your nice, sharable api should not be referencing something
                //  on the master page. So you could pass it all the way down. But that means you have to have this defined
                //  lots of places. Or you could create another js object to wrap this. There are several ways to do this and
                //  how you do it is up to you.
            }
        });
    }
})(jQuery);

然后我用每个实体的api扩展它

//User api object
//Uses the prototype method to make sure all objects of this type have required functions
var patientsApi = function () { }

userApi.prototype.getUsers = function (options,Id) {
    var config = $.extend({
        success: function () { },
        error: function () { }
    }, options);

    $.apiCall({
        url: '/Users/GetUser',
        data:{ID:Id},
        success: function (result) { config.success(result); }
    });
}

然后您可以从此页面调用

        var api = new userApi();
        var UserId= $("#UserId").val();

        api.getUsers({
            success: function (result) {          
            //Do some stuff
        }
     },userId);

答案 2 :(得分:0)

以下是我所做的事情:我无法承担所有功劳,因为我从一个例子中找到了部分。

    var varType;
    var varUrl;
    var varData;
    var varContentType;
    var varDataType;
    var varProcessData;          
    //Generic function to call ASMX/WCF  Service        
    function CallService() 
    {
            $.ajax({
                type        : varType, //GET or POST or PUT or DELETE verb
                url         : varUrl, // Location of the service
                data        : varData, //Data sent to server
                contentType : varContentType, // content type sent to server
                dataType    : varDataType, //Expected data format from server
                processdata : varProcessData, //True or False
                success     : function(msg) {//On Successfull service call
                ServiceSucceeded(msg);                    
                },
                error: ServiceFailed// When Service call fails
            });
    }

然后有一个成功的功能

function ServiceSucceeded(result) {//When service call is successful
 ....
}

然后是失败函数

 function ServiceFailed(result) {
 ...
 }

然后最后调用ajax函数的一个例子:

 function GetWCFJSON() {
        varType = "POST";
        varUrl = "service/WCFService.svc/GetMyData";
        varData = '{"States": "' + $('#ddlStates').val() + '"}';
        varContentType = "application/json; charset=utf-8";
        varDataType = "json";
        varProcessData = true;
        CallService();
    }