【问题标题】:Passing data from javascript to MVC Controller with multiple parameters使用多个参数将数据从 javascript 传递到 MVC 控制器
【发布时间】:2019-10-30 16:56:36
【问题描述】:

我有Controller OrderAssignmentRuleSet 和下面的ActionResult 方法

public ActionResult OrderAssignmentRuleSetEdit(string customerId, string Name= null, List<string> listOfItems = null)
        {

        }

下面是我的Javascript 将数据传递给我上面的controller 方法

     $("#rolesValues").change(function () {
               var id ='0001'                
               var name = 'admin'
               var listOfItems= [];
                //Populating listofItems with multiselect dropdown
                if ($('#ddlItemsList option:selected').length > 0) {
                    listOfItems = $.map($('#ddlItemsList option:selected'), function (item) {
                        return item.value;
                    });
                } 

            var data = { 
                    customerId: id,
                    Name: name,
                    listOfItems: listOfItems
                    }          


            $.ajax({
                    type: 'POST',
                    url: '/OrderAssignmentRuleSet/OrderAssignmentRuleSetEdit',
                    traditional : true,
                    data: data,
                    content: "application/json;",
                    dataType: "json",
                    success: function () {               
                    }
                });

我的问题是将两个strings(id 和名称)和一个array(listofItems 作为列表)传递给controller,当前代码不返回任何内容。请帮忙看看这段代码有什么问题?

【问题讨论】:

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


    【解决方案1】:

    您正在尝试以POST 方法发送您发布的数据。但是您正在尝试在操作方法的查询参数中收集这些数据。

    所以尝试创建一个类

    public class Sample
    {
        public string customerId { get; set; }
        public string Name { get; set; }
        public List<string> listOfItems { get; set; }
    }
    

    然后像这样修改你的action方法

    public ActionResult OrderAssignmentRuleSetEdit([FromBody] Sample sample)
    {
        //Your stuff here
    }
    

    【讨论】:

    • 我有课,但我想返回的列表有不同的数据类型。
    • 如果它不起作用,请尝试删除[FromBody]。让我知道
    • 实际上在我的模型中,订单列表实际上是一个字典,我想使用该参数来过滤另一个条件。
    • 能否请您向我展示listOfItems 中的示例数据,以便我告诉您哪种数据类型适合您。字典或列表
    【解决方案2】:

    你可以通过这种方式解决你的问题。

        myCustomFunction = function () {
        var model = {
            customerId: '',
            Name: '',
            listOfItems: ''
    
        };
        var url = '/OrderAssignmentRuleSet/OrderAssignmentRuleSetEdit';
        model.customerId = $("#customerId").val();// get customer id.
        model.Name = $("#Name").val();// get name;
        model.listOfItems = [];//get value of list;
    
            $.ajax({
                url: url,
                type: "Post",
                data: JSON.stringify(model),
                dataType: "json",
                contentType: "application/json"
    
            }).done(function (response) {
                console.log(response);
    
            }).fail(function (response) {
                console.log(response);
    
            });
    
        },
    

    //在服务器端获取数据,根据客户端需求制作模型。

    [HttpPost]

        public virtual JsonResult OrderAssignmentRuleSetEdit(MyCustomModel model)
        {
            try
            {
                ValidationViewModel msg = new ValidationViewModel();
    
                return Json(new { success = msg.Result, message = msg.Message }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
    
        }
    

    【讨论】:

      【解决方案3】:
      //Javascript method
      function postData(parsData)
          {
             var dataToSend = {  ParsData: parsData};
      
             var ReceivedData= JSON.stringify( dataToSend );
             $.ajax({
                       url: '@Url.Action("SetData")',
                       type: 'POST',
                       data: ReceivedData
             }).done(function (response) 
             {
                 console.log(response);
      
                 document.getElementById("result").innerHTML = response.resultHint;
                 document.getElementById("amount").innerHTML = response.resultAmount;
                 document.getElementById("image").src = response.imageUrl;
      
              });
          }
      //Javascript method Implementation
      postData("Fuking code");
      
      //C# Controller
      
      public class ReceivedData
              {
                  public string ParsData{ get; set; }
              }
      
              public class Result
              {
                  public string resultHint { get; set; }
                  public string resultAmount { get; set; }
                  public string imageUrl { get; set; }
                  public string decoded { get; set; }
              }
              [HttpPost]
              public ActionResult SetData(string receivedData)
              {
                  //var jss = new JavaScriptSerializer();
                 // ReceivedData decodedQR = new JavaScriptSerializer().Deserialize<ReceivedData>(receivedData);
                  // var dataObject = new JavaScriptSerializer().Deserialize(receivedData);
                  // .. do something with data object 
                  var jsonFromRequest = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
                  ReceivedData decodedQR = Newtonsoft.Json.JsonConvert.DeserializeObject<ReceivedData>(jsonFromRequest);
      
      
      
                  Result result= new Result();
      
                  result.resultHint = "Tem certeza que pretende permitir que o João Deposite o valor de ";
                  result.decoded = decodedQR.ParsData;
                  result.resultAmount = "200 MT";
                  result.imageUrl = "https://picsum.photos/id/237/200/300";
      
                  return Json(result);
              }
      

      Credit to:https://mestanzasoft.wordpress.com/2018/03/05/pass-data-from-asp-net-mvc-view-to-controller-with-ajax-and-json/

      【讨论】:

        猜你喜欢
        • 2016-08-14
        • 2015-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-10
        • 2022-01-25
        • 2015-12-28
        相关资源
        最近更新 更多