Add Item To String Array In Razor View

2019-09-19 13:28发布

问题:

I have a razor view where I am declaring a string array

@{
  var siteList = new List<string>();
  var stockTypeList = new List<string>();
}

There is an event on a multiselect that iterates over the selected values and I want to add the value of each of the selected items to this array

$('#stockTypeArea select :selected').each(function (i, selected) {
  @stockTypeList.Add(selected.val());
});

Currently this complains that it cannot resolve the 'selected' value. So my question is how can I add these string values to my string array?

The reason I need the string array is that I post this back as part of a @Html.Action

@HTML.Action("CustomReport_Data", "Reports", new { stockCodesList = stockTypeList })))

Perhaps there is a better way to capture this list of strings and pass back to the controller.

Even when I try and test the add method to my string array with:

@stockTypeList.Add("Test");

I get an error that:

Expression must return a value to render

回答1:

Razor code is running server-side.

jQuery is running client-side, and so is your event handler.

This:

$('#stockTypeArea select :selected').each(function (i, selected) {
  @stockTypeList.Add(selected.val());
});

Is a mix of both, but that can't ever work. selected.val() is client-side, @stockTypeList.Add(...) is server-side.

All of this explains your first error message.


@stockTypeList.Add("Test"); is also a Razor (server-side) statement. It adds a string to your list, but the method doesn't return a value (public void Add(T item)). the @ Razor operator takes the following expression and writes it as a URL encoded string to the client document, but you're not providing it a legal value (void).

This explains your second error.


@HTML.Action(...) generates a link with a url that can include query string parameters. These are normally coming from the 3rd argument in your call:

@HTML.Action("CustomReport_Data", "Reports", new { stockCodesList = stockTypeList })))

But at the time you execute this code (server-side) the list is of course empty.

You need to collect your string in client-side code (JavaScript array for example) and construct a URL for navigation using these strings.