Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...