【问题标题】:How to trigger an ASP.NET MVC 4 method in the Controller via ajax request如何通过 ajax 请求在 Controller 中触发 ASP.NET MVC 4 方法
【发布时间】:2021-09-08 15:48:16
【问题描述】:

这是我关于 SO 的第一个问题,所以这可能是一些基本问题。 我创建了一个按钮,以便通过 ajax 请求触发 Controller 中的方法。 我收到此错误: 消息无法反序列化为 MessageContract 类型 FXM.Ordering.WS.Contract.BoCreateAffiliateRequest,因为它没有默认(无参数)构造函数。

我尝试修改 ajax 请求并重新检查了我的代码的所有部分,但没有解决问题。

我的按钮:

 <div class="form-group">
            <div>
                <input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
            </div>
        </div>

ajax 请求:

<script type="text/javascript">
    $(function () {
        refreshGroups();
        $('#create-affiliate-button').click(function (e) {
            console.log("blahblahblah");

            var b = $("form").serialize();
            console.log("formvalues", b);

            $.ajax({
                url: "/en/AjaxUI/CreateAffiliate",
                type: "GET",
                dataType: "json",
                data: b,
       
                //error: function (jqXHR, exception) {
                //    failMessage();
                //}
            });
        });
    });

    function refreshGroups() {
        var pltf = "MT4_LIVE";
        var out = $('#MT4Group');
        if (pltf != null && pltf !== "") {
            $.ajax({
                url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
                data: {
                    platform: pltf, currency: "", withId : true
                },
                type: 'GET',
                beforeSend: function () {
                    $('#tpLoader').show();
                },
                complete: function () {
                    $('#tpLoader').hide();
                },
                success: function (data) {
                    populateDropDown(out, data);
                }
            });
        } else {
            out.empty();
            out.append($('<option></option>').val('').html(window.defaultSelection));
        }
    }

我试图在控制器中调用的方法


        public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
        {
            try
            {
                var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
                return Json("success");
            }
            catch (Exception e)
            {
                throw e;
            }
        }

我错过了什么? 在哪里/如何添加这个默认(无参数)构造函数?


按照建议添加无参数构造函数后更新。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FXM.BO.ViewModels
{
    public class NewAffiliateViewModel
    {
        public NewAffiliateViewModel()
        {
        }

        public int Id { get; set; }

        public string AffiliateName { get; set; }

        public string Email { get; set; }


        public int Employee { get; set; }


        public int MT4Group { get; set; }
    }
}

【问题讨论】:

  • 您可能需要走使用依赖注入的路线,或者作为回答,使用默认构造函数来初始化构造函数参数所需的任何内容。没有更多上下文很难知道。

标签: c# asp.net ajax model-view-controller


【解决方案1】:

添加无参数构造或添加到您的 NewAffiliateViewModel 类中:

public class NewAffiliateViewModel
{
    public NewAffiliateViewModel()
    {
    
    }
}

【讨论】:

  • 感谢您的回复。奇怪的是,在添加无参数构造函数后,我仍然遇到同样的错误。
  • 你的控制器呢?那有带参数的构造函数吗?
【解决方案2】:

尝试为此使用@Url.Action()

       $.ajax({
            url: "@Url.Action("CreateAffiliate", "AjaxUI")",
            type: "GET",
            dataType: "json",
            data: {
                     newAffiliateViewModel : b
            },
   
            //error: function (jqXHR, exception) {
            //    failMessage();
            //}
        });

#EDIT 1:

所以你可以传递复杂的对象,比如你的类。您需要在控制器动作中解析 JSON,并在动作参数中设置:

     public JsonResult CreateAffiliate(string newAffiliateJSON)
            {
                try
                {
                    //here you need to deserizlize variable newAffiliateJSON 
                    //to object try this helper: https://json2csharp.com/
                    //something like that Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); (and you need to create new class, that describes your json (get it on site i write upper))
                    var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
                    return Json("success");
                }
            catch (Exception e)
            {
                throw e;
            }
        }

所以像我说的那样重写 JS 代码和 Action 方法。在 ajax 请求中,您必须像在控制器操作中一样命名数据参数

data: { newAffiliateJSON: b} 

【讨论】:

  • 感谢您的回复。添加我得到的代码后:对象引用未设置为对象的实例。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。可能是什么问题?
  • @TomSawyer 你在哪里得到这个错误?可以附上图片吗?
猜你喜欢
  • 2015-08-22
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多