Asp.net mvc 如何保持MVCjQueryAjax文章的干燥?

Asp.net mvc 如何保持MVCjQueryAjax文章的干燥?,asp.net-mvc,ajax,jquery,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, { **myActionParameterNam

我正在使用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);
             }

         });


     });
$(“#我的复选框”).change(函数(){
var值=$(this.attr(“选中”);
var url='';
$.ajaxSetup({cache:false});
$.post(url,{**myActionParameterName**:value},函数(数据){
如果(data.result!=“成功”){
警报(数据错误);
}
});
});

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

简单回答:没有。在一天结束时,AJAX需要知道如何以这种或那种方式调用参数

你说的是抽象,而不是“不要重复你自己”的策略。DRY的意思是“不要重复你的逻辑不止一次”,而不是“不要引用变量”。如果是这样的话,你就不能对变量或参数进行任何形式的引用,因为你在技术上重复变量的名称

您必须引用一些东西,这些东西将被多次引用,一次是客户端,一次是服务器端。当然,您可以将其抽象为其他内容,但在一天结束时,可能最简单的方法是引用您的动作参数,而不必担心它

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


现在,如果您在JavaScript中多次引用该JSON对象,或者多次奇怪地构造它,那么DRY就开始发挥作用了,您应该创建一个方法,在该方法中可以传递数据来构造它。

我就是这么做的:我不能把所有功劳都归功于我从一个示例中找到的部分

    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();
    }

我建议使用jQuery.extend()功能简化调用并创建javascript api。退房

我使用这样的标准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);

参数名称是否与用于呈现包含AJAX代码的视图的模型上的属性名称相关?不,属性名称不同。这让事情变得有点棘手。。。使用反射来查找方法参数名称感觉太过分了