Home How can I post an array of string to ASP.NET MVC Controller without a form?
Reply: 0

How can I post an array of string to ASP.NET MVC Controller without a form?

user1335
1#
user1335 Published in May 28, 2018, 5:04 am

I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function.

I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though.

Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far:

function generateList(selectedValues) {
   var s = {
      values: selectedValues //selectedValues is an array of string
   };
   $.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
}

And then my Controller looks like this

public ActionResult GenerateList(List<string> values)
{
    //do something
}

All I managed to get is a "null" in the controller parameter...

Any tips?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.330138 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO