2

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 3

3

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

I have class but the list I wanted to return has different datatype.
if its not work then try with removing [FromBody]. and let me know
Actually in my Model the list of orders is actually a Dictionary, I wanted to use that parameter to filter another criteria.
could you please show me sample data inside listOfItems so I'll let you know which data type will be suitable for you. either dictionary or List
0

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

    }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.