davoudm20
davoudm20

Reputation: 15

How pass Array to action with Ajax.ActionLink from view?

I am using razor and passing an array to a controller. the array contains string type. example array in view :

@{
.
.
.
   string[] menustatus = ViewBag.MENUS;
}
.
.
.
@Ajax.ActionLink("linkname",ActionName, ControllerName, new { status = menustatus }, new AjaxOptions { HttpMethod = "Post" }, null)

my controller is :

public ActionResult ActoinName(params string[] status)
{
}

status Variable contains value of "system.string[]". I expect the array values ​​are passed to the action.

Upvotes: 1

Views: 1577

Answers (1)

Boris Parfenenkov
Boris Parfenenkov

Reputation: 3279

You cannot pass array in ActionLink like this. Because by default mvc.net call ToString method and it returns system.string[]. But you can use two alternative ways. First is join array of strings before sending, and then (in controller) split them into array, like this:

... new { status = String.Join(";", menustatus)) ...

in view. And this in controller:

public ActionResult ActoinName(string allStatus) {
  var status = allStatus.Split(new[] {";"});

Or you can use ajax post with jquery:

<a href="javascript:ajaxCall()" id="ajaxCall">linkAjax</a>
<script>
    function ajaxCall() {
        $.ajax({
            traditional: true,
            type: "POST",
            url: "@Url.Action("ActionName")",
            data: {status: [
                @foreach (var st in menustatus)
                {
                    @:'@st', 
                }
                ]
            },
            success: function(data) { /*doing something*/ }
        });
    };
</script>

Upvotes: 2

Related Questions