Passing data from javascript to MVC Controller with multiple parameters

Viewed 2580

I have Controller OrderAssignmentRuleSet with following ActionResult Method

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

        }

And below is my Javascript to pass data to my above controller method

     $("#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 () {               
                    }
                });

My problem is to pass two strings (id and name) and one array (listofItems as a list) to controller, Current code doesn't return anything. Please help whats wrong with this code?

3 Answers

You are trying to send your posted data in POST method. But you are trying to collect those data in query parameters in action method.

So try to create a class like

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

And then modify your action method like

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

you can solve your problem in this way.

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

        });

    },

//In Server side to get data, make a model as client side requirement.

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

    }
//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/

Related