user3173346
user3173346

Reputation: 85

Passing a string array to mvc controllers using ajax

I need to pass list of strings from multiple select to the controller. Though the requirement looked very simple to me, I was breaking my head for the past hour in this. I have did a fair research on this, but unable to succeed.

Below is my Javascript code. Please ignore the comments. I was successfully able to fetch the list of items in the multiple select. While i do the ajax call, I get the error "Object reference not set an instance of an object.

function submitForm() {
    var selected = $('#selectedTasks option').map(function(){ 
        return this.value 
    }).get()
    var postData = { selectedTasks : selected } //corrected as suggested

    //selectedTasks = JSON.stringify({ 'selectedTasks': selected });
    alert(postData);

    $.ajax({
        type: "POST",
        //contentType: 'application/json; charset=utf-8',
        url: '@Url.Action("AssignTasks", "MonthEndApp")',
        dataType: 'json',
        data: postData,
        traditional: true,
        success: function (data) {                
            alert("Success");
        },
        error: function (xhr) {                    
            alert(xhr.responseText);
        } 
    });
}

MonthEndAppController.cs

[HttpPost]
public void AssignTasks(List<String> selectedTasks)
{
    //do something
}

Can someone guide me where exactly I have gone wrong? Can someone suggest me what is wrong?

EDIT : As suggested by Mr. Rory I have made the java script changes. Now the Java script part works absolutely fine. But the Controller is not getting called when the ajax request is made. Can someone help me out if something wrong in the call made to controller ?

Upvotes: 2

Views: 3475

Answers (2)

Sebastian Estrada
Sebastian Estrada

Reputation: 307

Have you tried with string[] instead of List<String> ?

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The parameter your AssignTasks action is expecting is called selectedTasks, not values:

var postData = { selectedTasks: selected };

Also note that when debugging anything in JS you should always use console.log() over alert(), as the latter coerces all types to a string, which means you're not seeing a true representation of the actual value.

Upvotes: 1

Related Questions